I need to write a php script that will download all text files on a google drive folder to local folder. The code below is able to download all files on the gdrive but the content of the downloaded files is all wrong. The content seems to be an error log instead of actual content of file.
Sample content of file after download:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"errors": [
{
"message": "The request is missing a valid API key.",
"domain": "global",
"reason": "forbidden"
}
]
}
}
Got this code on the web:
<?php
require 'vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=D:\username\folder\credentials.json');
function downloadFilesFromFolder($folderId, $destinationPath, $service)
{
// List all files in the folder
$pageToken = null;
do {
$parameters = array(
'q' => "'$folderId' in parents and mimeType='text/plain'",
'fields' => 'files(id, name)',
'pageToken' => $pageToken,
);
$results = $service->files->listFiles($parameters);
if (count($results->getFiles()) == 0) {
print "No text files found in the specified folder.\n";
} else {
foreach ($results->getFiles() as $file) {
$fileId = $file->getId();
$fileName = $file->getName();
$fileDownloadUrl = "https://www.googleapis.com/drive/v3/files/$fileId/export?mimeType=text/plain";
$response = $service->getClient()->getHttpClient()->request('GET', $fileDownloadUrl, ['sink' => "$destinationPath\\$fileName"]);
if ($response->getStatusCode() === 200) {
echo "Downloaded: $fileName\n";
} else {
echo "Failed to download: $fileName\n";
}
}
}
$pageToken = $results->getNextPageToken();
} while ($pageToken);
}
$folderId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$destinationPath = 'D:\\username\\folder\\';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(Google_Service_Drive::DRIVE);
$service = new Google_Service_Drive($client);
downloadFilesFromFolder($folderId, $destinationPath, $service);
I need to download the files from gdrive with its actual content.