列出Google云端硬盘中的所有文件

时间:2014-11-04 09:00:47

标签: php google-oauth google-api-php-client google-drive-api

我想列出我的Google云端硬盘中的所有文件到我的“DriveFiles.php”文件,我可以在其中显示文件及其详细信息。我是初学者,所以完整的代码会有所帮助。感谢。

我的代码:

<?php


require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once 'google-api-php-client/src/io/Google_HttpRequest.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';

// initialize a client with application credentials and required scopes.
$client = new Google_Client();
$client->setClientId('CLIENT_ID');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('REDIRECT_URI');
$client->setScopes(array(
          'https://www.googleapis.com/auth/drive',
          'https://www.googleapis.com/auth/userinfo.email',
          'https://www.googleapis.com/auth/userinfo.profile'));
$client->setUseObjects(true);


if (isset($_GET['code']))
   {
   session_start();
   print_r($_SESSION);
   $client->authenticate($_GET['code']);
   $_SESSION['token'] = $client->getAccessToken();
   $client->setAccessToken($_SESSION['token']);
   // initialize the drive service with the client.
   $services = new Google_DriveService($client);
   retrieveAllFiles($services);    

  }



 if(!$client->getAccessToken()){
   $authUrl = $client->createAuthUrl();
   echo '<a class="login" href="'.$authUrl.'">Login</a>';
   }


 function retrieveAllFiles($service) {
   $result = array();
   $pageToken = NULL;

          do {
            try {
              $parameters = array();
              if ($pageToken) {
                $parameters['pageToken'] = $pageToken;
              }
              $files = $service->files->listFiles($parameters);

              $result = array_merge($result, $files->getItems());
              $pageToken = $files->getNextPageToken();
            } catch (Exception $e) {
              print "An error occurred: " . $e->getMessage();
              $pageToken = NULL;
            }
          } while ($pageToken);
          return $result;
        }
        ?>

当我执行代码时,我收到以下错误:

  

致命错误:未捕获的异常'Google_Exception',消息为'Cant   在经过身份验证后添加服务   d:\ GT_local \公用\谷歌API的PHP客户端的\ src \ Google_Client.php:115   堆栈跟踪:#0   d:\ GT_local \公用\谷歌的API的PHP客户端的\ src \的contrib \ Google_DriveService.php(1258):   Google_Client-&gt; addService('drive','v2')#1   d:\ GT_local \公用\ quickstart.php(55):   Google_DriveService-&gt; __ construct(Object(Google_Client))#2 {main}   投入   “FILE_LOCATION(C:// google-api-php-client \ src \ Google_Client.php on line)   115)“

我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试在脚本顶部启动会话,并尝试在必须执行任何操作之前执行所有身份验证。还可以使用最新的API,以便您可以使用此库:

require_once '/src/Google/autoload.php';
require_once '/src/Google/Client.php';
require_once '/src/Google/Service/Oauth2.php';
require_once '/src/Google/Service/Drive.php';