My code has service account credentials but it not returning expected data - anyone spot any issues with it? It is returning an empty object - am I not accessing the right part of the $file when I try to return the data? The example at https://developers.google.com/drive/api/guides/folder#php_2 to move folders notes this line:
$file = $driveService->files->get($fileId, array('fields' => 'parents'));
But when I use that the response is an error exception and the file is not found. The file id and folder id are both correct.
$fileId = '{myfileid}'; //image file id
$folderId = '{myFolderId}'; //folder to move into
use Google\Client;
use Google\Service\Drive;
use Google\Service\Drive\DriveFile;
function moveFileToFolder($fileId, $folderId)
{
try {
$client = new Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=/var/www/https/html/googleapis/drive/service_credentials.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$emptyFileMetadata = new DriveFile();
// Retrieve the existing parents to remove
$file = $driveService->files->get($fileId, [
'fields' => 'parents',
'alt' => 'media'
]);
echo json_encode($file);
// // Access the parent information
// $parents = $file->getParents();
// foreach ($parents as $parent) {
// echo 'Parent ID: ' . $parent . '<br>';
// }
$previousParents = join(',', $file->parents);
// Move the file to the new folder
$file = $driveService->files->update($fileId, $emptyFileMetadata, array(
'addParents' => $folderId,
'removeParents' => $previousParents,
'supportsAllDrives' => true,
'fields' => 'id, parents'
));
return $file->parents;
} catch (Exception $e) {
echo "Error Message: " . $e;
}
}
moveFileToFolder($fileId, $folderId);
I have used the same setup for other successful requests bar the line:
$emptyFileMetadata = new DriveFile();
and is subsequent use.
I believe your goal is as follows.
In this case, how about the following answer?
When 'alt' => 'media'
is used to $driveService->files->get()
, the file content is retrieved instead of the file metadata. So, I think that fields
is not used.
I guessed that in your situation, you might have wanted to retrieve the parent folder ID of the file of $fileId
on the shared drive. If my understanding is correct, how about the following modification?
$file = $driveService->files->get($fileId, array('fields' => 'parents'));
$file = $driveService->files->get($fileId, array('fields' => 'parents', 'supportsAllDrives' => true));
By this modification, the file metadata of $fileId
on the shared drive is retrieved.