[英]Uploading the files to same google drive using php
我想知道是否有任何方法可以使用 php 將文件直接上傳到我們自己的 Google 驅動器,目前我正在使用這樣的方法。
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code'] = 'ya2-------------------------OZXiA';
//file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('/assets/new--detils.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
但這顯示了一個錯誤
致命錯誤:未捕獲的異常Google_AuthException
帶有消息“獲取 OAuth2 訪問令牌時出錯,消息: /var/www/path/src/auth/Google_OAuth2.php:115
: Google_AuthException
“invalid_grant”
在這里,我使用為該應用程序生成的$_GET['code'] = 'ya2-------------------------OZXiA'
,
任何人都可以提出一種方法來做到這一點,在此先感謝。
不確定它是否有幫助,但我通過谷歌代碼發現了這個......
“當您嘗試使用相同的授權代碼時,您將收到 invalid_grant 錯誤。”
我在這里找到它: https : //code.google.com/p/google-api-php-client/issues/detail?id=94
不知道這對你有沒有幫助...
還找到了本教程: http : //25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
**$drive->setAccessType('offline');**
$authUrl = $client->createAuthUrl();
echo $authUrl;
現在轉到 auth url 並獲取刷新令牌和其他內容。 確保這是您第一次請求許可,否則您將無法獲得刷新令牌,這是將來制作 authtoken 所必需的。 如果您已經授予權限,只需轉到您的 google 帳戶並撤銷該應用程序的權限。 這也是您要重定向的文件中應該包含的內容。
$tokeninfo = $drive->getAccessToken();
print_r($tokeninfo);
現在將令牌信息保存在“token.json”之類的文件中。
現在返回到包含上傳代碼的原始文件。
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$drive->setAccessType('offline');
$service = new Google_Service_Drive($drive);
$refreshToken = "Your refresh token";
/* get it from token.json and it will look some like this 1**\/**asasfasfsfsd
remove the \ since this is actually json encoded.*/
$tokens = file_get_contents(TOKEN); /*TOKEN = the token.json file*/
$drive->setAccessToken($tokens);
if ($drive->isAccessTokenExpired()) {
$drive->refreshToken($refreshToken);
file_put_contents(TOKEN,$drive->getAccessToken());
}
Now you have done the authentication and just need to upload the file.
if ($drive->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->title ="the file name";
/*the upload code can be found in the examples*/
}
注意您上傳的文件不能被其他人下載,需要設置googlepermissions才能共享文件。 如果您需要編碼以添加權限,只需發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.