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

11,522

Solution 1

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;
?>

Solution 2

I recommend you look into using a service account. A service account is like a dummy user which is pre authenticated. This means that you can share a folder on your google drive account with the service account and the service account will be able to upload to it. I have an article on how Service accounts work. Google Developers console Service account

There are a few things you need to remember when working with service accounts though. Mainly permissions when the service account uploads a file by default it owns the file so you will need to grant your personal account permissions to the file after it is uploaded. Its just an extra step.

The PHP client library has a sample for using service account authentication but it doesn't have drive you will have to alter the books part to be google drive. Service-account.php

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

This may also help my google drive samples

Share:
11,522
user1371961
Author by

user1371961

Updated on June 16, 2022

Comments

  • user1371961
    user1371961 almost 2 years

    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.

  • mevsme
    mevsme over 3 years
    Is this code still valid? I get Fatal error: Uncaught Google\Service\Exception: { "error": "unauthorized_client", "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested." } in D:\Google Drive\web\www\src\Http\REST.php:128