Simple how to Integrate Google Drive API with PHP. 2


Do you want to Integrate Google Drive API with PHP? In this tutorial we will look at how to simply integrate the google drive api with php. If you want to integrate your PHP script to your google drive account doesn’t have to be hard. In fact using the PHP client library it can be quite strait forward. In this post we are going to look at how to create a simple script designed to run on a server. Not this code will NOT run hosted as a web application. This is just a console script.

Create Installed app credentials

The first thing you will need is to create a credetials.json file. This can be created on google cloud console make sure to create native credentials.

Composer

You will need to install the php client library this can be done using composer. Instructions for this can be found on the Google api PHP client library README. I recommend checking for the most recent version number on the php packages repository

composer require google/apiclient:^2.12.1

Authorization

This code is designed to store the user authorization within a file called token.json. After you have authorized the app once a refresh token will be stored there. Then when the app runs again it will be able to use the refresh token to request a new access token in order to access your google drive account.

Warning refresh tokens will expire after seven days while your project is set to testing in google cloud console. Go to the oauth screen and set it to production and the refresh token will stop expiring.

https://developers.google.com/identity/protocols/oauth2#expiration

The section of the code which handles the authorization for us is as follows

$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);

$client->setAccessToken($accessToken);

Copy the authorization link and place it in any web browser. Authorize the application. You will see a 400 error in the browser window when it is complete ignore this. This is due to the removal of oob. If you look at the url bar within that string returned is a code. http://localhost/?code=4/0AX4XfWgU3p6QqHeogZ7NitClTYDt3Tf_bv-A1kI4UoEm0CzpHiXrpD8TEnLUxta-SKFLlA&scope=https://www.googleapis.com/auth/drive.readonly It is this code that you add to your application. You can only use the code once.

The code will then fetch an access token with this authorization code.

Using the following code we store the token returned into the token.json file for later use

// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));

Warning refresh tokens will expire after seven days while your project is set to testing in google cloud console. Go to the oauth screen and set it to production and the refresh token will stop expiring.

https://developers.google.com/identity/protocols/oauth2#expiration

Google Drive API with PHP

Now that your app is authorized you can call the Google Drive API. Just remember that each method has one or more scopes that are required in order to access that method. You can find the scope needed within the documentation for each method. For example File.list will show you which scope you must have requested authorization from. In this script I am only asking for read only scope which means if you try to do a file.create it will not work. If you change the scope in this script remember to delete the token.json file so that the script will request authorization of the user again.

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

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

use Google\Client;
use Google\Service\Drive;

/**
* Returns an authorized API client.
* @return Client the authorized client object
*/
function getClient()
{
$client = new Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes('https://www.googleapis.com/auth/drive.readonly');
$client->setAuthConfig('C:\YouTube\dev\credentials.json');
$client->setAccessType('offline');
$client->setRedirectUri("http://127.0.0.1");
$client->setPrompt('select_account consent');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} 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);

$client->setAccessToken($accessToken);

// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}


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

// Print the next 10 events on the user's calendar.
try{


$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)',
'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
'orderBy' => 'name'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();

if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;

printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}

Conclusion

Authorizing your php script to connect to the google drive api is quite simple once you have the code. Using the PHP client library and allowing it to handle all of the authorization for us makes our life a lot easer.

Remember to create installed app credentials to run this script. I have a video that shows how. Just remember to enable the Google drive api under library


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 thoughts on “Simple how to Integrate Google Drive API with PHP.