Create Files On Google Drive using PHP

Create Files On Google Drive using PHP

In order to create a file in google drive, foremost we need to create a project in Google developer console.

Follow the below steps to work with Google Drive APIs

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.
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.

Step 1: Turn on the Drive API

  1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
  2. On the Add credentials to your project page, click the Cancel button.
  3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product nameif not already set, and click the Save button.
  4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  5. Select the application type Other, enter the name “Drive API Quickstart”, and click the Create button.
  6. Click OK to dismiss the resulting dialog.
  7. Click the file_download (Download JSON) button to the right of the client ID.
  8. Move this file to your working directory and rename it client_secret.json.

Step 2: Install the Google Client Library

Run the following command to install the library using composer:

php composer.phar 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 index.php in your working directory and copy in the following code:

 

<?php

set_include_path('vendor/google/apiclient-services/src');

require_once 'vendor/autoload.php';


session_start();

$client = new Google_Client();
$client->setAuthConfig('/cs.json');
$client->addScope(Google_Service_Drive::DRIVE);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
 
 
 
 $client->setAccessToken($_SESSION['access_token']);
 $drive = new Google_Service_Drive($client);
 
 insertFile($drive, "tester", "arenrtcheck", null, "text/plain", "TestFile");
} else {
 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . 'oauth2callback.php';
 header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


function insertFile($service, $title, $description, $parentId, $mimeType, $data) {
 $file = new Google_Service_Drive_DriveFile();
 $file->setName($title);
 $file->setDescription($description);
 $file->setMimeType($mimeType);

// Set the parent folder.
 if ($parentId != null) {
 $parent = new Google_Service_Drive_ParentReference();
 $parent->setId($parentId);
 $file->setParents(array($parent));
 }

try {
// $data = file_get_contents($filename);

$createdFile = $service->files->create($file, array(
 'data' => $data,
 'mimeType' => $mimeType,
 ));

// Uncomment the following line to print the File ID
 // print 'File ID: %s' % $createdFile->getId();

return $createdFile;
 } catch (Exception $e) {
 print "An error occurred: " . $e->getMessage();
 }
}

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

<?php
require_once 'vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig('../gtcclient/cs.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . 'oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE);

if (! isset($_GET['code'])) {
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
 $client->authenticate($_GET['code']);
 $_SESSION['access_token'] = $client->getAccessToken();
 $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
 header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

While working on domains make sure to add the valid redirects on developer console

Authorized redirect URIs

For use with requests from a web server. This is the path in your application that users are redirected to after they have authenticated with Google. The path will be appended with the authorization code for access. Must have a protocol. Cannot contain URL fragments or relative paths. Cannot be a public IP address

 

Pros : You make minimize the external disk space and personalize the data. Since the drive is revision control you will get all the flavors related to revisions by default where you will never loose the data. The advantages brought by the customizations on the google drive are endless.

Cons:- Whenever the token gets expired there has to be a manual login to work with the app. There is no way to automate the data backups or schedulers to run without a manual login.

For any question on google drive API drop an email to agileplmwz@gmail.com

 

Leave a Reply

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