PHP Extension Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get


<?php

// The version number (9_5_0) should match version of the Chilkat extension used, omitting the micro-version number.
// For example, if using Chilkat v9.5.0.48, then include as shown here:
include("chilkat_9_5_0.php");

$rest = new CkRest();

//   Provide a previously obtained OAuth2 access token.
$oauth2 = new CkOAuth2();
$oauth2->put_AccessToken('OAUTH2_ACCESS_TOKEN');
$rest->SetAuthOAuth2($oauth2);

$success = $rest->Connect('www.googleapis.com',443,true,true);
if ($success != true) {
    print $rest->lastErrorText() . "\n";
    exit;
}

$rest->AddQueryParam('includeTeamDriveItems','true');
$rest->AddQueryParam('supportsTeamDrives','true');
$rest->AddQueryParam('alt','media');

//  First send the HTTP request.
$success = $rest->SendReqNoBody('GET','/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl');
if ($success != true) {
    print $rest->lastErrorText() . "\n";
    exit;
}

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
$statusCode = $rest->ReadResponseHeader();
if ($statusCode < 0) {
    print $rest->lastErrorText() . "\n";
    exit;
}

if ($statusCode != 200) {
    print 'Received error response code: ' . $statusCode . "\n";
    //  Read the error response body.
    $sbErrResponse = new CkStringBuilder();
    $success = $rest->ReadRespSb($sbErrResponse);
    if ($success != true) {
        print $rest->lastErrorText() . "\n";
        exit;
    }

    print 'Error response:' . $sbErrResponse->getAsString() . "\n";
    exit;
}

//  Stream the response body to the output file.
$respBodyStream = new CkStream();
$respBodyStream->put_SinkFile('/someDirectory/penguins.jpg');
$success = $rest->ReadRespBodyStream($respBodyStream,true);
if ($success != true) {
    print $rest->lastErrorText() . "\n";
    exit;
}

print 'Example Completed.' . "\n";

?>