如何使用PHP获取我在Google云端硬盘中拥有的所有文件的列表?

时间:2013-08-27 08:12:25

标签: google-drive-api

我想使用我的“DriveFiles.php”文件列出我的Google云端硬盘中的所有文件,我可以在其中显示文件及其详细信息。

我是初学者,所以完整的代码会有所帮助。

感谢。

我的代码:

<?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;
}
?>

当我执行时,我收到错误:

Fatal error: Uncaught exception 'Google_Exception' with message 'Cant add services after having authenticated' in D:\GT_local\Public\google-api-php-client\src\Google_Client.php:115 Stack trace: #0 D:\GT_local\Public\google-api-php-client\src\contrib\Google_DriveService.php(1258): Google_Client->addService('drive', 'v2') #1 D:\GT_local\Public\quickstart.php(55): Google_DriveService->__construct(Object(Google_Client)) #2 {main} thrown in "FILE_LOCATION(C://google-api-php-client\src\Google_Client.php on line 115)"

我应该做什么?

1 个答案:

答案 0 :(得分:2)

files.list docs包含一个带分页的工作示例:您可以使用DrEdit作为样板项目。