Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a google drive download file to a directory using php

Am trying download a google drive files to a directory using the code below. when I run the code it only open the content of the file on the browser as per code below

// authentication google drive goes here

$file = $service->files->get($fileId);


  $downloadUrl = $file->getDownloadUrl();
    $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
   echo $content= $httpRequest->getResponseBody();

Here is how am trying to download it to a directory called destinations

// Open file handle for output.

$content = $service->files->get($fileId, array("alt" => "media"));

// Open file handle for output.

$handle = fopen("/download", "w+");

// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.

while (!$content->eof()) {
        fwrite($handle, $content->read(1024));
}

fclose($handle);
echo "success";

here is the error i got

Fatal error: Uncaught Error: Call to a member function eof() on string in C:\xampp\htdocs\download.php

like image 673
jmarkatti Avatar asked Sep 19 '25 05:09

jmarkatti


1 Answers

  • You want to download a file from Google Drive to the specific directory using google/apiclient with php.
  • The files you want to download are yours and/or shared with you.

If my understanding is correct, how about this modification?

Modification point:

  • Please use getBody() for $content.
    • $content->getBody()->eof()
    • $content->getBody()->read(1024)

Modified script:

In this modification, the filename is also retrieved by Drive API and used for saving the downloaded file. If you don't want to use it, please remove the script for it.

$fileId = "###"; // Please set the file ID.

// Retrieve filename.
$file = $service->files->get($fileId);
$fileName = $file->getName();

// Download a file.
$content = $service->files->get($fileId, array("alt" => "media"));
$handle = fopen("./download/".$fileName, "w+"); // Modified
while (!$content->getBody()->eof()) { // Modified
    fwrite($handle, $content->getBody()->read(1024)); // Modified
}
fclose($handle);
echo "success";
  • In above script, the downloaded file is saved to the directory of ./download/.

Note:

  • When the method of Files: get of Drive API, the files except for Google Docs (Google Spreadsheet, Google Document, Google Slides and so on) can be downloaded. If you want to download Google Docs, please use the method of Files: export. Please be careful this.
    • So in above modified script, it supposes that you are trying to download the files except for Google Docs.

References:

  • PHP Quickstart
  • Download files
  • Files: get
  • Files: export

If I misunderstood your question and this was not the result you want, I apologize.

like image 121
Tanaike Avatar answered Sep 20 '25 21:09

Tanaike