Reap The Ultimate Benefits Of Google Drive And Dropbox Using API

Introduction
Google drive and Dropbox have huge room for storing files and performing operations like save, edit, delete, share, etc. This storage platform provides service to perform these operations using other applications via API. The API can be used for different platforms like web, Android, iOS. The main agenda for such applications is to store any files like images, doc files, sheets, etc., stored in the device, and you access it anywhere and everywhere. Below is an illustration to use google drive and dropbox import/export files using API.
Google Drive API
Google Drive API gives the facility to develop applications that can use the maximum advantage of the google drive cloud storage. Using this API, you can integrate your application with Google Drive to access the stored file and to store files.
This diagram illustrates relationship between your Google Drive app, Google Drive, and Google Drive API.
[ Image Source: https://developers.google.com/drive/api/v3/about-sdk ]
Avail Oneself Of Google Drive API
- Download/upload files using Google Drive.
- Look for files and folders stored in Google Drive. Create multiplex search queries that return any of the file metadata fields in the file resource.
- Sharing of files, folders, and drives to collaborate on content.
- Merge with the Google Picker API to search all files in Google Drive, then return the file name, URL, last modified date, and user.
Introduction of PHP
PHP stands for Hypertext Preprocessor. Its server-side scripting language is used for creating static and dynamic web pages. It’s free to download and use. It is easy to comprehend in comparison to other languages like java, .Net. It also supports third-party support in our web application without having more complexity.
Prerequisites
- PHP version must be greater than 5.4
- The composer must be installed.
- Need Google account enabled with google drive.
Step 1: Turn On The Drive API
- First, you need to login to the Google API console using this link.
https://console.developers.google.com. - Then you need to go to the “Credential menu” in the console and register your application with needful details.
- Now you will get Client ID, Secret Client ID, and Developer Key. You can directly put these keys in your code, or you can download the JSON file for these keys and include this file in your application.
Step 2: Install The Google Client Library
Go to your code’s root directory using the command line and use the below command to install the google client library.
composer require google/apiclient:^2.0
Step 3: Set Up The Code
Include vendor autoload file
<?php
require __DIR__ . ‘/vendor/autoload.php’;if (php_sapi_name() != ‘cli’) {
throw new Exception(‘This application must be run on the command line.’);
}
The below code does connect with the google account and returns the token. We need to store it in a token.json file, which should be created in your code’s root folder.
function getClient()
{
$client = new Google_Client();
$client->setApplicationName(‘Google Drive API PHP Quickstart’);
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig(‘credentials.json’);
$client->setAccessType(‘offline’);
$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;
}
Below is the code connected with the drive of the logged-in google account and open a picker with the list of files and folders which are stored in the drive.
// 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());
}
}
* Note: You will get a file id if you select a file in google drive picker. To save this file in your local room, you need to call curl.
There are many more options available for filter and searching files from google drive picker.
Export To Google Drive
Below code connect with google drive account and get code in response.
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId(”);
$client->setClientSecret(”);
$client->setRedirectUri(”);
$client->setScopes(array(‘https://www.googleapis.com/auth/drive.file’));
Using code, we can set the token and access the google drive file service. We can set file property using params and directly create files on google drive.
if (isset($_GET[‘code’]) || (isset($_SESSION[‘access_token’]) && $_SESSION[‘access_token’])) {
if (isset($_GET[‘code’])) {
$client->authenticate($_GET[‘code’]);
$_SESSION[‘access_token’] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION[‘access_token’]);$service = new Google_Service_Drive($client);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().’.jpg’);
$file->setDescription(‘A test document’);
$file->setMimeType(‘image/jpeg’);$data = file_get_contents(‘a.jpg’);
$createdFile = $service->files->create($file, array(
‘data’ => $data,
‘mimeType’ => ‘image/jpeg’,
‘uploadType’ => ‘multipart’
));print_r($createdFile);
} else {
$authUrl = $client->createAuthUrl();
header(‘Location: ‘ . $authUrl);
exit();
}
Alternatively, you can also create a folder on google drive and upload files in the folder. For that, you need to pass the parent id (folder id) while uploading files.
Below is the list of available mime types supported in google drive.
$mime_types= array(
“xls” =>’application/vnd.ms-excel’,
“xlsx” =>’application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’,
“xml” =>’text/xml’,
“ods”=>’application/vnd.oasis.opendocument.spreadsheet’,
“csv”=>’text/plain’,
“tmpl”=>’text/plain’,
“pdf”=> ‘application/pdf’,
“php”=>’application/x-httpd-php’,
“jpg”=>’image/jpeg’,
“png”=>’image/png’,
“gif”=>’image/gif’,
“bmp”=>’image/bmp’,
“txt”=>’text/plain’,
“doc”=>’application/msword’,
“js”=>’text/js’,
“swf”=>’application/x-shockwave-flash’,
“mp3″=>’audio/mpeg’,
“zip”=>’application/zip’,
“rar”=>’application/rar’,
“tar”=>’application/tar’,
“arj”=>’application/arj’,
“cab”=>’application/cab’,
“html”=>’text/html’,
“htm”=>’text/html’,
“default”=>’application/octet-stream’,
“folder”=>’application/vnd.google-apps.folder’
);
Dropbox
Dropbox offers SDKs for several programming languages. This will help the user to select or save content from dropbox.
There are two methods through which we can select or save files from dropbox.
1. Chooser
The Chooser is a rapid path to retrieve files from Dropbox into your web, Android, or iOS app. It’s a compact element that permits your app to receive files from Dropbox without having the burden of authentication or managing uploads and storage.
2. Saver
The Saver is the simple method to add files to your users’ Dropbox accounts. You can download these files, irrespective of their size, available for your computer within two clicks.
Dropbox Credential
You need to create an account in Dropbox.
Go in the developer option and create your app; after that, you will get a dropbox app key and secret key.
Chooser
This method provides code in javascript, Android, iOS.
Below is an example of javascript.
First, you need to include the below js file in your code.
<script type=”text/javascript” src=”https://www.dropbox.com/static/api/2/dropins.js” id=”dropboxjs” data-app-key=”YOUR_APP_KEY”></script>
There are two ways to activate the chooser dropbox on your website.
Give predefined button Like
var button = Dropbox.createChooseButton(options);
document.getElementById(“container”).appendChild(button);
If you want your custom design then use:
Dropbox.choose(options);
Both methods need single options as defined below:
options = {
// Required. Called when a user selects an item in the Chooser.
success: function(files) {
alert(“Here’s the file link: ” + files[0].link)
},// Optional. Called when the user closes the dialog without selecting a file
// and does not include any parameters.
cancel: function() {},
// Optional. “preview” (default) is a preview link to the document for sharing,
// “direct” is an expiring link to download the contents of the file. For more
// information about link types, see Link types below.
linkType: “preview”, // or “direct”// Optional. A value of false (default) limits selection to a single file, while
// true enables multiple file selection.
multiselect: false, // or true// Optional. This is a list of file extensions. If specified, the user will
// only be able to select files with these extensions. You may also specify
// file types, such as “video” or “images” in the list. For more information,
// see File types below. By default, all extensions are allowed.
extensions: [‘.pdf’, ‘.doc’, ‘.docx’],// Optional. A value of false (default) limits selection to files,
// while true allows the user to select both folders and files.
// You cannot specify `linkType: “direct”` when using `folderselect: true`.
folderselect: false, // or true// Optional. A limit on the size of each file that may be selected, in bytes.
// If specified, the user will only be able to select files with size
// less than or equal to this limit.
// For the purposes of this option, folders have size zero.
sizeLimit: 1024, // or any positive number
};
Managing Response
You will get a response as an object in the success callback method.
If you have selected a multi-select option true, you will get an array of objects; otherwise, it will be a single object.
The response contains the below information.
file = {
// Unique ID for the file, compatible with Dropbox API v2.
id: “id:…”,// Name of the file.
name: “filename.txt”,// URL to access the file, which varies depending on the linkType specified when the
// Chooser was triggered.
link: “https://…”,// Size of the file in bytes.
bytes: 464,// URL to a 64x64px icon for the file based on the file’s extension.
icon: “https://…”,// A thumbnail URL generated when the user selects images and videos.
// If the user didn’t select an image or video, no thumbnail will be included.
thumbnailLink: “https://…?bounding_box=75&mode=fit”,// Boolean, whether or not the file is actually a directory
isDir: false,
};
In the link attribute, you will get your file.
Link Types
Chooser provides two type id links.
- Preview Link
Its user-friendly preview page of the file. - Direct link
Display the content of the file and the help of downloading the file. This link expires after 4 hours, so make sure to download content quickly and do not use this link to display content on the browser.
This link also supports CORS.
Supported File Types
[ Screenshot Source: https://www.dropbox.com/developers/chooser ]
Supported Browsers
If the browser does not support these SDKs, you can check it using the below code.
Dropbox.isBrowserSupported().
Saver
Mentioned here is a simple and easy way to save the file in your Dropbox account.
For export files in dropbox you need to add below in your code.
<script type=”text/javascript” src=”https://www.dropbox.com/static/api/2/dropins.js” id=”dropboxjs” data-app-key=”YOUR_APP_KEY”></script>
For creating a save to dropbox button, you can turn <a> tag into the saver button by adding the class “dropbox-saver” to it.
<a href=”https://dl.dropboxusercontent.com/s/deroi5nwm6u7gdf/advice.png” class=”dropbox-saver”></a>
It’s compulsory to add “dropbox-saver” in a tag. This method supports HTTP and HTTPS URL.
If you want to add a save button programmatically, then you need to add the below script. The code below is for multiple file upload to dropbox.
var options = {
files: [
// You can specify up to 100 files.
{‘url’: ‘…’, ‘filename’: ‘…’},
{‘url’: ‘…’, ‘filename’: ‘…’},
// …
],// Success is called once all files have been successfully added to the user’s
// Dropbox, although they may not have synced to the user’s devices yet.
success: function () {
// Indicate to the user that the files have been saved.
alert(“Success! Files saved to your Dropbox.”);
},// Progress is called periodically to update the application on the progress
// of the user’s downloads. The value passed to this callback is a float
// between 0 and 1. The progress callback is guaranteed to be called at least
// once with the value 1.
progress: function (progress) {},// Cancel is called if the user presses the Cancel button or closes the Saver.
cancel: function () {},// Error is called in the event of an unexpected response from the server
// hosting the files, such as not being able to find a file. This callback is
// also called if there is an error on Dropbox or if the user is over quota.
error: function (errorMessage) {}
};
var button = Dropbox.createSaveButton(options);
document.getElementById(“container”).appendChild(button);
On the occasions when you want to upload a single file, then you need to add:
Dropbox.createSaveButton(url, filename, options);
The success option is used to indicate to the user that files have been successfully uploaded.
Triggering The Saver From Javascript
For the saving method, you can trigger the saver button from javascript.
Dropbox.save(options);
You can also check content consistency by adding content hash options in the file.
var options = {
files: [
// You can specify up to 100 files.
{‘url’: ‘…’, ‘filename’: ‘…’, ‘contentHash’: ‘…’},
{‘url’: ‘…’, ‘filename’: ‘…’},
// …
],
/* Same settings as above … */
}
Conclusion
As you all know, web apps like Google Drive and Dropbox provide a third-party platform to use this functionality through programming. It gives users the liberty to manage their applications using these functions without any complexity. The steps given above can be used to integrate Google Drive and Dropbox’s APIs with all the custom web development projects and mobile apps for Android and iOS. Nowadays, this third API support will help most users manage and use their stored files directly to any app. It will help users to have their files anytime, anywhere, and now with any app. If you’re curious and want to further know more about the Google Drive and Drop API integration, get in touch with us!
No, it’s not possible in google drive, but dropbox has that functionality.
Allow only 500 users per app. Please find more information on this: https://www.dropbox.com/business/plans-comparison
When we create a developer account on google, it creates a free trial account for $300. After the limit exceeds, you need to do payment for accessing the service.
Satyam Vishwakarma
Thank you so much for providing this knowledge.
Comments are closed.