不需要PHP Google Drive API身份验证

时间:2015-03-17 23:33:09

标签: php authentication google-api google-drive-api

我正在开发一个使用Google驱动API的PHP代码。当您拥有该驱动器的Google帐户登录时,API可以上传文件。我的问题是它可以上传文件,即使拥有它的谷歌帐户没有登录,例如,没有谷歌帐户登录或其他谷歌帐户登录。我只想让驱动器公开,任何人都可以上传文件。

这是我使用的代码。

<?php

  function setGoogleDriveUpload($clientID, $secretKey, $redirecturi, $newfilename, $uploadfile){
    session_start();
    $url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    $url = $url_array[0];
    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_DriveService.php';   

    $client = new Google_Client();
    $client->setClientId($clientID);
    $client->setClientSecret($secretKey);
    $client->setRedirectUri($redirecturi);
    $client->setScopes(array('https://www.googleapis.com/auth/drive'));

    if (isset($_GET['code'])) {
       $_SESSION['accessToken'] = $client->authenticate($_GET['code']);
       header('location:'.$url);exit;
    } elseif (!isset($_SESSION['accessToken'])) {
       $client->authenticate();
    }

    $client->setAccessToken($_SESSION['accessToken']);
    $service = new Google_DriveService($client);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file = new Google_DriveFile();

    $file_path = $uploadfile;
    $mime_type = finfo_file($finfo, $file_path);
    $file->setTitle($newfilename);
    $file->setDescription('This is a '.$mime_type.' document');
    $file->setMimeType($mime_type);
    $service->files->insert(
        $file,
        array(
            'data' => file_get_contents($file_path),
            'mimeType' => $mime_type
        )
    );

    finfo_close($finfo);

}

1 个答案:

答案 0 :(得分:0)

&#34;我的问题是它可以上传文件,即使拥有它的Google帐户没有登录&#34;

是的,前提是帐户所有者已获得离线访问权限。在这种情况下,您的应用程序将收到一个刷新令牌,您可以存储并用于在您想要上传文件时生成访问令牌。