PHP Quickstart

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple PHP command-line application that makes requests to the Google Drive Activity API.

Prerequisites

To run this quickstart, you'll need:

  • PHP 5.4 or greater with the command-line interface (CLI) and JSON extension installed.
  • The Composer dependency management tool.
  • A G Suite account with Google Drive enabled.

Step 1: Turn on the Google Drive Activity API

Click this button to create a new console project and automatically enable the Google Drive Activity API:

Enable the Google Drive Activity API

This opens a new dialog. In the dialog, do the following:

  1. Select + Create a new project.
  2. Enter the name "Google Drive Activity API Quickstart".
  3. Download the configuration file.
  4. Move the downloaded file to your working directory.

Step 2: Install the Google Client Library

composer require google/apiclient:^2.0

See the library's installation page for the alternative installation options.

Step 3: Set up the sample

Create a file named quickstart.php in your working directory and copy in the following code:

drive/activity/quickstart.php
<?php
require __DIR__ . '/vendor/autoload.php';

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('Google Drive Activity API Quickstart');
    $client->setScopes(implode(' ', array(
      Google_Service_Appsactivity::ACTIVITY,
      Google_Service_Drive::DRIVE_METADATA_READONLY)
    ));
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = 'token.json';
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } 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->fetchAccessTokenWithAuthCode($authCode);

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

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

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

// Print the recent activity in your Google Drive.
$optParams = array(
    'source' => 'drive.google.com',
    'drive.ancestorId' => 'root',
    'pageSize' => 10,
);
$results = $service->activities->listActivities($optParams);

if (count($results->getActivities()) == 0) {
    print "No activity.\n";
} else {
    print "Recent activity:\n";
    foreach ($results->getActivities() as $activity) {
        $event = $activity->getCombinedEvent();
        $user = $event->getUser();
        $target = $event->getTarget();
        if (empty($user) || empty($target)) {
            continue;
        }
        $time = date(DateTime::RFC3339, $event->getEventTimeMillis() / 1000);
        printf("%s: %s, %s, %s (%s)\n", $time, $user->getName(),
                $event->getPrimaryEventType(), $target->getName(),
                $target->getMimeType());
    }
}

Step 4: Run the sample

Run the sample using the following command:

php quickstart.php

The first time you run the sample, it will prompt you to authorize access:

  1. Browse to the provided URL in your web browser.

    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.
  3. Copy the code you're given, paste it into the command-line prompt, and press Enter.

Notes

  • Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.
  • The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see Using OAuth 2.0 for Web Server Applications.

Further reading

Send feedback about...

Google Drive Activity API
Need help? Visit our support page.