首页 > 解决方案 > 默默地无法通过 PHP SDK 将图像推送到用户的 Google Drive

问题描述

我正在制作一个开源应用程序,用户可以使用 PHP SDK 将他们的 Facebook 相册备份到谷歌驱动器。我完成了 facebook 部分,现在坚持使用 google 写得很好的文档。所以这里是我的工作方式是一步一步的:

用户身份验证:我所有的请求和回调都在一个 PHP 文件中进行管理,类似于 API。所以这是处理将文档上传到谷歌的请求的代码块:

<?php
session_start();
require_once __DIR__.'/classes/facebook.class.php';
require_once __DIR__.'/classes/drive.class.php';
$fb = new Facebook();
$google = Drive::getInstance();
$query = $_REQUEST['i'];
switch($query){
        case "backup_req":
            $agent = $google->getAgent();
            if(!isset($_SESSION['google_access_token'])){
                $_SESSION['album_temp'] = $_REQUEST['album'];
                header("location: ".filter_var($agent->createAuthUrl(), FILTER_SANITIZE_URL));
            } else{
                $google->uploadAlbum($fb, $_REQUEST['album']);
            }
        break;
        case "google_callback":
            $agent = $google->getAgent();
            if(!isset($_SESSION['google_access_token'])){
                $code = $_GET['code']; // just to keep the code neat.. no need to store in other var!
                $res = $google->getAgent()->authenticate($code); // hope this works
                $_SESSION['google_access_token'] = $agent->getAccessToken();
            }
            $google->uploadAlbum($fb, $_SESSION['album_temp']);
        break;
}

这里我要做的是,如果会话中没有谷歌的访问令牌,我们将用户重定向到谷歌的登录页面。完成后重定向到同一个文件,但这次请求google_callback连同代码。然后将其存储到会话中,我们继续执行uploadAlbum方法。

注意,我已经回显了服务器的内容,是的,我确实获得了访问令牌和刷新令牌

现在,为了上传专辑,Drive 类中有 4 个方法,这是一个单例。这是代码:

    class Drive{
    private static $instance;
    private $fileRequest;
    private $mimeType;
    private $filename;
    private $path;
    private $client;
    private $clientId = "<client-id>";
    private $clientSecret = "<client-secret>";
    private final function __construct(){
        $this->client = new Google_Client();
        $this->client->setApplicationName("fb album backup tool");
        $this->client->setClientId($this->clientId);
        $this->client->setClientSecret($this->clientSecret);
        $this->client->setRedirectUri("https://fbrtc.sameer-manek.com/fb_caller.php?i=google_callback");
        $this->client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
        $this->client->setAccessType("offline");
        $this->client->setApprovalPrompt('force');
    }
    public static function getInstance(){
        if(self::$instance == null) {
            self::$instance = new Drive();
        }
        return self::$instance;
    }
    public function getAgent(){
        return $this->client;
    }
    public function uploadAlbum($fb, $album){
            $nodes = $fb->get_photos($album);
            $client = new GearmanClient();
            $client->addServer();
            foreach ($nodes as $node) {
                //$client->addTask('init', $node['picture']);
                try{
                    $data = file_get_contents($node['picture']);
                    $saveto = __DIR__."/../scripts/tmp/".rand().".jpg";
                    $file = fopen($saveto, "w+");
                    fwrite($file, $data);
                    fclose($file);
                    $this->init($saveto);
                    echo "uploaded ".$saveto."\n";
                } catch(Exception $e) {
                    return false;
                }

            }
            return true;
            //$client->runTasks();
    }
    public function init($file){
        $at = $_SESSION['google_access_token']['access_token'];
        $this->client->setAccessToken($at);
        $this->fileRequest = $file;
        $client = $this->client;
        //$client->refreshToken($_SESSION['google_access_token']['refreshToken']);
        $tokens = $client->getAccessToken();
        $client->setAccessToken($tokens);
        $client->setDefer(true);
        $this->client->setAccessToken($at);
        $this->processFile();
    }
    public function processFile(){
        $fileRequest = $this->fileRequest;
        $path_parts = pathinfo($this->fileRequest);
        $this->path = $path_parts['dirname'];
        $this->fileName = $path_parts['basename'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $this->mimeType = finfo_file($finfo, $fileRequest);
        finfo_close($finfo);
        $this->upload();
    }
    public function upload(){
        $client = $this->client;
        $service = new Google_Service_Drive($this->client);
        //Insert a file
        $file = new Google_Service_Drive_DriveFile();
        $file->setName($this->fileName.'.jpg');
        $file->setDescription('A test document');
        $file->setMimeType('image/jpeg');
        $data = file_get_contents($this->fileRequest);
        $createdFile = $service->files->create($file, array(
              'data' => $data,
              'mimeType' => 'image/jpeg',
              'uploadType' => 'multipart'
        ));
    }
}

uploadAlbum()方法是从请求的相册中获取图像。 init()方法是准备对象以上传该图像(这里我们使用为对象分配访问令牌) processFile()方法是获取和存储有关图像的信息。 upload()方法实际上是将图像上传到用户的谷歌驱动器。

执行此操作后,没有产生异常,也没有产生任何错误,但是当我交叉检查时,图像没有上传到驱动器..

我无法确定问题所在,请帮助我解决此错误。谢谢。

[编辑] 我 var_dumped 的内容$createdFile并在屏幕上转储以下内容:

object(GuzzleHttp\Psr7\Request)#73 (7) { ["method":"GuzzleHttp\Psr7\Request":private]=> string(4) "POST" ["requestTarget":"GuzzleHttp\Psr7\Request":private]=> NULL ["uri":"GuzzleHttp\Psr7\Request":private]=> object(GuzzleHttp\Psr7\Uri)#69 (7) { ["scheme":"GuzzleHttp\Psr7\Uri":private]=> string(5) "https" ["userInfo":"GuzzleHttp\Psr7\Uri":private]=> string(0) "" ["host":"GuzzleHttp\Psr7\Uri":private]=> string(18) "www.googleapis.com" ["port":"GuzzleHttp\Psr7\Uri":private]=> NULL ["path":"GuzzleHttp\Psr7\Uri":private]=> string(22) "/upload/drive/v3/files" ["query":"GuzzleHttp\Psr7\Uri":private]=> string(20) "uploadType=multipart" ["fragment":"GuzzleHttp\Psr7\Uri":private]=> string(0) "" } ["headers":"GuzzleHttp\Psr7\Request":private]=> array(3) { ["Host"]=> array(1) { [0]=> string(18) "www.googleapis.com" } ["content-type"]=> array(1) { [0]=> string(37) "multipart/related; boundary=344323595" } ["X-Php-Expected-Class"]=> array(1) { [0]=> string(30) "Google_Service_Drive_DriveFile" } } ["headerNames":"GuzzleHttp\Psr7\Request":private]=> array(3) { ["content-type"]=> string(12) "content-type" ["host"]=> string(4) "Host" ["x-php-expected-class"]=> string(20) "X-Php-Expected-Class" } ["protocol":"GuzzleHttp\Psr7\Request":private]=> string(3) "1.1" ["stream":"GuzzleHttp\Psr7\Request":private]=> object(GuzzleHttp\Psr7\Stream)#67 (7) { ["stream":"GuzzleHttp\Psr7\Stream":private]=> resource(11) of type (stream) ["size":"GuzzleHttp\Psr7\Stream":private]=> NULL ["seekable":"GuzzleHttp\Psr7\Stream":private]=> bool(true) ["readable":"GuzzleHttp\Psr7\Stream":private]=> bool(true) ["writable":"GuzzleHttp\Psr7\Stream":private]=> bool(true) ["uri":"GuzzleHttp\Psr7\Stream":private]=> string(10) "php://temp" ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=> array(0) { } } } uploaded /sites/facebook_backup/classes/../scripts/tmp/264708337.jpg

这是GitHub 存储库的链接以供参考。

标签: phpgoogle-apigoogle-drive-apigoogle-api-php-clientgoogle-php-sdk

解决方案


推荐阅读