Home / PHP / Uploading files to Google Drive with PHP

Uploading files to Google Drive with PHP

Google Drive, Google’s popular online storage service, has an API that allows us to work with different programming languages to manage all the files stored in our own application. In this article, I show a simple example of how to upload them to our account through PHP.

Following the same method as in previous articles, to develop the example I have built a simple application which you can find on GitHub. This example consists of an index.php file that contains all the code of the application and from where the google library (google-api-php-client folder) and the HTML view (index.phtml file) are also called. In the view, all the files contained in the files folder are simply displayed. All the files that we place in this folder will be the ones that will be uploaded to our Drive account.

Download Code From my Git Repository https://github.com/fareed543/Uploading-files-to-Google-Drive-with-PHP

This article is based on the tutorial published by Google, although as you can see I have modified a few points to facilitate its compression.

file upload PHP google drive

Before messing with the code, we must enable the API for our application. To do this we must create a new project in the Google APIs Console and follow the steps indicated in the first point of the tutorial. We must bear in mind that in the services section of the console there are two services related to Drive: the SDK and the API. We must enable both, which by default does not happen, and if we do not, we would get an error of type HTTP 403 “Access Not Configured Error”. All this is not mentioned in the tutorial.

Once we have obtained the keys to our id and user secret we download the latest version of the API library for PHP. This library is the one I have hosted the google-api-php-client folder.

Now, we went to study the code. We will start with the view:

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Google Drive Example App</title>
</head>
<body>

<ul>
<?php foreach ($files as $file) { ?>

<li><?php echo $file; ?></li>

<?php } ?>
</ul>

<form method="post" action="<?php echo $url; ?>">
<input type="submit" value="enviar" name="submit">
</form>

</body>
</html>

Here we simply show a list of the names of all the files contained in the files folder. By clicking on the submit button of the form we will upload all of them to our Google Drive account. When accessing the page for the first time we will be redirected to the Google page where we will have to give permission to the API so that it can access and manage the files hosted in our account. Once we click on “allow access” we will be redirected back to our application.

And then our php code:

// index.php

<?php session_start(); $url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']); $url = $url_array[0]; require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; $client = new Google_Client(); $client->setClientId('your client id');
$client->setClientSecret('your client secret');
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code'])) {
$_SESSION['accessToken'] = $client->authenticate($_GET['code']);
header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
$client->authenticate();
}
$files= array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
$dir->close();
if (!empty($_POST)) {
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
header('location:'.$url);exit;
}
include 'index.phtml';

We are going to study this code in parts:

session_start();
$url_array = explode(‘?’, ‘http://’.$_SERVER [‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’]);
$url = $url_array[0];
require_once ‘google-api-php-client/src/Google_Client.php’;
require_once ‘google-api-php-client/src/contrib/Google_DriveService.php’;

First, we open a session, which will be necessary to avoid having to confirm the API permissions each time we reload the page. Next, I define the URL of our app and in case it contains a variable of type $ _GET (sent by Google when confirming the permissions), we ignore it. Finally, I call the two Google libraries: the Google_Client class will allow us to configure our user account and Google_DriveService our Drive account.

$client = new Google_Client();
$client->setClientId('your client id');
$client->setClientSecret('your client secret');
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

We define our user account of the Google API. This is where we will have to enter our id and user secret previously obtained.

if (isset($_GET['code'])) {
$_SESSION['accessToken'] = $client->authenticate($_GET['code']);
header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
$client->authenticate();
}

As I mentioned above, when we confirm the API access request, we are redirected back to our application and the variable “code” is passed to us via GET. If it exists, we pass it as a parameter to the authenticate method of the Google_Client object that returns a value for which we opened our session. Contrary to what it might seem, this return value contains a JSON which in turn contains 6 values, one of which is the “acces_token” as such.

On the contrary, when we access the application for the first time, we call the method without passing any parameter and we are redirected to the API access permission confirmation screen.

$files= array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
$dir->close();
if (!empty($_POST)) {
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
header('location:'.$url);exit;
}
include 'index.phtml';

Finally, we save in an array the names of the files contained in our files folder. It will be this array that we use to upload and also show in the view (included at the end of the script) all our files.

If we have sent the form, we will upload all the files to Drive, to which we can define their title, description and content type properties through an instance of the Google_DriveFile class. To do this we must first pass the JSON parameter with all the access token information stored in our session and instantiate the Google_DriveService class to which we passed as the dependency the previously configured $ client object.

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

TechO2 Hyderabad Web Developer Interview Questions

After done with the technical round, they conduct a system test over skype. here is …

Leave a Reply

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