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

问题描述 投票:0回答:1

我想使用我的“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)"

我应该做什么?

php google-drive-api
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.