4

I need an help to make the right decision about how to make use of google api.

I want to develop a script to connect server to server (without any Oauth2 connection) to my google drive folder in order to display google drive file and folder in a web page. I'll also set a cron job to do an action if some files are updated.

Is this possibile? In google cloud platform I found the drive api with the Server-to-server interaction. Is this the right solution?

Thanks you!

Luca
  • 848
  • 1
  • 14
  • 33
  • 1
    Look up service account. As long as the service account has access to the file on your drive account (add it like you would share it with any other user) It will be able to access it. then check out https://developers.google.com/drive/v2/reference/files/watch – Linda Lawton - DaImTo Feb 23 '16 at 13:00
  • It requires oauth or public file. This could not be the way for me. Thank you for your help! – Luca Feb 23 '16 at 13:20
  • Service accounts are Oauth yes but its preauthorized Oauth. So you don't get the pop up window asking for the user to grant you access that's why its ideal for server applications like cron jobs. The file doesn't have to be public on google drive you just have to grant the service account email address access to the file like you would any other user (that's the preauthorization part) – Linda Lawton - DaImTo Feb 23 '16 at 13:24
  • 2
    Here is a tutorial I wrote about service accounts it might help you understand what I mean http://www.daimto.com/google-developer-console-service-account/ – Linda Lawton - DaImTo Feb 23 '16 at 13:25

1 Answers1

6

https://developers.google.com/drive/v3/web/quickstart/php

Over here you'll find the way to enable the API. From that point you can use the library.

The site will give a sample:

<?php
require __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Drive::DRIVE_METADATA_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfigFile(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = file_get_contents($credentialsPath);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->authenticate($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, $accessToken);
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->refreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, $client->getAccessToken());
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => "nextPageToken, files(id, name)"
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s (%s)\n", $file->getName(), $file->getId());
  }
}

This will show 10 files just as they say.

This is (in my opinion) the best way.

WowThatsLoud
  • 115
  • 7