谷歌驱动器上传PHP

时间:2016-08-26 16:26:32

标签: google-drive-api google-oauth

require_once ('../google-api-php/vendor/autoload.php');


$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xxxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));

session_start();

if (isset($_GET['code']) || (isset($_SESSION['access_token']) &&         $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
} else
    $client->setAccessToken($_SESSION['access_token']);

$service = new Google_Service_Drive($client);

//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');

$data = file_get_contents('a.jpg');

$createdFile = $service->files->create($file, array(
      'data' => $data,
      'mimeType' => 'image/jpeg',
      'uploadType' => 'multipart'
    ));

print_r($createdFile);

} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();

这是错误:

Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } }.....

但客户端ID和客户端秘密ara copy from my console ...

2 个答案:

答案 0 :(得分:0)

现在脚本工作,2回答:

1:如果文件夹不存在,如何在驱动器上创建文件夹?

2:如何设置文件夹以插入上传的文件。

答案 1 :(得分:0)

脚本有效,但当会话过期或更改网页浏览器时,我必须插入我的Google凭据,这是一种没有插入凭据的工作方式吗?