I want to write a server php script which will access my google drive and copy a file there. The server has to save credentials for my google drive and not ask for authorisation. All the examples I saw describe web applications there various users can perform actions on their drives. For example here https://developers.google.com/drive/v3/web/quickstart/php How can I save all the needed credentials on my server.
After a long research and reading google documentation and examples I found a way that works for me.
Finally this is working code snippet:
<?php
require_once '/path/to/google-api-php-client/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive']);
$client->setSubject('email_of_account@you_want_to_work.for');
$service = new Google_Service_Drive($client);
//Create a new folder
$fileMetadata = new Google_Service_Drive_DriveFile(
array('name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array('fields' => 'id'));
echo $file->id;
?>
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