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
If my understanding is correct, how about this modification?
getBody()
for $content
.
$content->getBody()->eof()
$content->getBody()->read(1024)
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";
./download/
.If I misunderstood your question and this was not the result you want, I apologize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With