简体   繁体   中英

File download from Google API v3 in PHP

Have been looking all over for downloading a file from google drive with the API as mentioned here . In the flow, was able to pass the authentication of the user, and was able to list the files with the below code.

 echo "<br>" . count($results->getFiles()). " File(s) found" ; 
        echo "<hr>";
        foreach ($results->getFiles() as $file) {
            echo "File Name is " . $file->getName() . " And file ID is ". $file->getId() . " Type is ".$file->getMimeType() ."<br><pre>";
            print_r($file);
            echo "</pre><hr>";
        }

And the output is something like

100 File(s) found
File Name is invoice receipt.pdf And file ID is 0B5CWXJTNwALMOEJkdzFvMVVsVFE Type is application/pdf
Google_Service_Drive_DriveFile Object
(
    [collection_key:protected] => spaces
    [appProperties] => 
    [capabilitiesType:protected] => Google_Service_Drive_DriveFileCapabilities
    [capabilitiesDataType:protected] => 
    [contentHintsType:protected] => Google_Service_Drive_DriveFileContentHints
    [contentHintsDataType:protected] => 
    [createdTime] => 
    [description] => 
    [explicitlyTrashed] => 
    [fileExtension] => 
    [folderColorRgb] => 
    [fullFileExtension] => 
    [headRevisionId] => 
    [iconLink] => 
    [id] => 0B5CWXJTNwALMOEJkdzFvMVVsVFE
    [imageMediaMetadataType:protected] => Google_Service_Drive_DriveFileImageMediaMetadata
    [imageMediaMetadataDataType:protected] => 
    [isAppAuthorized] => 
    [kind] => drive#file
    [lastModifyingUserType:protected] => Google_Service_Drive_User
    [lastModifyingUserDataType:protected] => 
    [md5Checksum] => 
    [mimeType] => application/pdf
    [modifiedByMeTime] => 
    [modifiedTime] => 
    [name] => invoice receipt.pdf
    [originalFilename] => 
    [ownedByMe] => 
    [ownersType:protected] => Google_Service_Drive_User
    [ownersDataType:protected] => array
    [parents] => 
    [permissionsType:protected] => Google_Service_Drive_Permission
    [permissionsDataType:protected] => array
    [properties] => 
    [quotaBytesUsed] => 
    [shared] => 
    [sharedWithMeTime] => 
    [sharingUserType:protected] => Google_Service_Drive_User
    [sharingUserDataType:protected] => 
    [size] => 
    [spaces] => 
    [starred] => 
    [thumbnailLink] => 
    [trashed] => 
    [version] => 
    [videoMediaMetadataType:protected] => Google_Service_Drive_DriveFileVideoMediaMetadata
    [videoMediaMetadataDataType:protected] => 
    [viewedByMe] => 
    [viewedByMeTime] => 
    [viewersCanCopyContent] => 
    [webContentLink] => 
    [webViewLink] => 
    [writersCanShare] => 
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
        )

    [processed:protected] => Array
        (
        )

)

Now, trying to apply the download code as below

$fileId = '0B5CWXJTNwALMOEJkdzFvMVVsVFE';
        $content = $drive_service->files->get($fileId,  array(
            'alt' => 'media' ));
        echo "<pre>";
        print_r($content->getHeaders());
        foreach ($content->getHeaders() as $name => $values) {

        header($name . ': ' . implode(', ', $values[0]));
        }

The file is not downloaded but was able to see the output like below

Array
(
    [X-GUploader-UploadID] => Array
        (
            [0] => AEnB2UrDOQ-mYxNd5tE5ctVr01jVTnh3ZykKviCBnEOjDRGtT_EIT2nbHLEM_f-2pZ22anDJpqMzbISzhcTTZY3PgsDj69PE-w
        )

    [Content-Type] => Array
        (
            [0] => application/pdf
        )

    [Content-Disposition] => Array
        (
            [0] => attachment
        )

    [Vary] => Array
        (
            [0] => Origin
            [1] => X-Origin
        )

    [Expires] => Array
        (
            [0] => Tue, 23 Aug 2016 13:20:18 GMT
        )

    [Date] => Array
        (
            [0] => Tue, 23 Aug 2016 13:20:18 GMT
        )

    [Cache-Control] => Array
        (
            [0] => private, max-age=0, must-revalidate
        )

    [Content-Length] => Array
        (
            [0] => 80277
        )

    [X-Goog-Hash] => Array
        (
            [0] => crc32c=5yKN2g==
        )

    [Server] => Array
        (
            [0] => UploadServer
        )

    [Alternate-Protocol] => Array
        (
            [0] => 443:quic
        )

    [Alt-Svc] => Array
        (
            [0] => quic=":443"; ma=2592000; v="35,34,33,32,31,30"
        )

)

Question : How do I download the file?

EDIT

Based on paulo answer, have created two files as below.This is working for image/png, application/octet-stream, application/pdf types, however have issues with zip/rar files (error : This site can't be reached )

test.php

<?php
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
{
    $client->setAccessToken($_SESSION['access_token']);
    $drive_service = new Google_Service_Drive($client);
    $results = $drive_service->files->listFiles();
    if (count($results->getFiles()) == 0) 
    {
        echo "No files found";
    } 
    else 
    {
        echo "<br>" . count($results->getFiles()). " File(s) found" ; 
        echo "<br><table><thead><th>File Name</th><th>File Type</th><th>Download Link</th></thead><tbody>";
        foreach ($results->getFiles() as $file) {
            echo "<tr><td>" . $file->getName() . "</td><td>" . $file->getMimeType() ."</td><td><a href='gdrivedownlaod.php?fileid=". $file->getId() . "&type=" . $file->getMimeType() . "&name=" . $file->getName() . "' target='blank'>Download</a></td></tr>";// ."<br><pre>";
            }
            echo "</tbody></table>";
    }

} 
else 
{
    $redirect_uri = 'https://abcd.co/oauth2callback';
    echo "Hello, <a href='" . $redirect_uri . "'>Log in with Drive</a>";
}

and gdrivedownlaod.php as

<?php
require_once __DIR__ . '/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (isset($_GET['name']) && isset($_GET['type'])) {
//echo "We will download " . $_GET['name'] . " type " . $_GET['type'] . " with file id " . $_GET['fileid'];
    $fileId=$_GET['fileid'];
    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
    {
        $client->setAccessToken($_SESSION['access_token']);
        $drive_service = new Google_Service_Drive($client);
        $content = $drive_service->files->get($fileId,  array(
            'alt' => 'media' ));
                $fileName = $_GET['name'];
        $headers = $content->getHeaders();

        foreach ($headers as $name => $values) {
            header($name . ': ' . implode(', ', $values));
        }
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        echo $content->getBody();
        //echo "<script>window.close();</script>";
        exit;
    }
    else
    {
        session_destroy();
        session_unset();
        header('Location: test.php'); 
    }

}
else
echo "incorrect files ";
$fileName = 'xpto.pdf';
$driveService = new Google_Service_Drive($client);
$content = $driveService->files->get($fileId, array(
    'alt' => 'media'));

$headers = $content->getHeaders();
foreach ($headers as $name => $values) {
    header($name . ': ' . implode(', ', $values));
}
header('Content-Disposition: attachment; filename="' . $fileName . '"');
echo $content->getBody();
exit;

as indicated above $content->getHeaders() has provided an expected output of the corresponding header information of your HTTP request.

to retrieve the file content, you will need $content->getResponseBody() , and then call file_put_contents in order to save the data into a local file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM