Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access my google drive from php script without manual authorisation

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.

like image 630
user1371961 Avatar asked Dec 03 '22 23:12

user1371961


1 Answers

After a long research and reading google documentation and examples I found a way that works for me.

  1. You need a service account. This account will access the google drive data.
  2. I work with google domain, therefore I needed to grant domain wide authority to this service account.
  3. Here you can find how to create a service account and grant it domain wide authority however this link does not has PHP examples
  4. Here you can find the same instructions with PHP examples
  5. Please pay attention that you need JSON type key file when you create a service account.
  6. I used Google Application Default Credentials.

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;
?>
like image 147
user1371961 Avatar answered Dec 11 '22 17:12

user1371961