Google Drive PHP API下载文件


Google Drive PHP API Download file

我在使用phpapi从谷歌驱动器下载文件时遇到问题。我设法将文件上传到文件夹中的谷歌驱动器,$service->files->insert返回给我的文件资源具有属性downloadUrl,但当我重定向到该url时,它不起作用。我得到401错误。为什么会发生这种情况?我需要做什么才能做到这一点?

这里的代码:

<?php
require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrive/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
header("Location: $authUrl");

和代码.php

require_once 'vendor/autoload.php';
session_start();
$client_id = 'xxx';
$client_secret = 'yyy';
$redirect_uri = 'http://localhost/GoogleDrivePayload/code.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setApprovalPrompt('force');
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['upload_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
    $client->setAccessToken($_SESSION['upload_token']);
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
}
if ($client->getAccessToken()) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle("hello.exe");
    $file->setDescription("LALALALALAL");
    $file->setMimeType('application/x-msdos-program');
    $parent = new Google_Service_Drive_ParentReference();
    $parent->setId("zzz");
    $file->setParents(array($parent));
    $data = file_get_contents('hello.exe');
    $createdFile = $service->files->insert($file, array(
            'data' => $data,
            'mimeType' => 'application/x-msdos-program',
            'uploadType' => 'multipart',
            "visibility" => "DEFAULT"
    ));
    header("Location: " . $createdFile->downloadUrl);
}

downloadUrl正是它所说的,即PHP应用程序可以用来获取文件的URL。你几乎永远不会将浏览器重定向到该URL,如果你这样做了(你可能真的不想),你需要在URL上附加一个有效的访问令牌来修复401。