Automated backups to Google Drive with PHP API

Where do you keep backups? I guess that depends on what do you backup. You might have a very clever answer for a business critical data but what about less important content? The best example would be a private blog. It will hurt if you lose your data but the odds are you’re not willing to pay for any reliable storage. If you care enough to backup it’s going to be to another server (if you own one), your own laptop or external hard drive. S3 is gaining popularity but not everybody have and want to open account on Amazon. On the other hand there is one reliable storage, which is 100% free and almost everybody have access to it. Yes, I’m talking about Google Drive.

In order to integrate your program with Google Drive you need to create a Google API project. You can do it at Google console page.

001-create-app

Press “Create Project” button and select services you want to use with the project. For the purpose of this example “Drive API” is enough.

002-services

Once the service is enabled click on API Access from the left hand side navigation.

003-api-access

Click on “Create an OAuth 2.0 client ID” button. Make up a project name and click “next”. On the Client ID settings page choose “Service Account” as the application type.

004-service-account

Press “Create client ID” button. Click “Download private key” to download… you guess it – private key! You need it to access your account. Bear in mind you can download it only once.

005-download-private-key

Now your service account it created. You will need the client id and email address in a second. Leave the Google console page open.

006-service-account

There is one important thing you need to be aware of. Service account is not your Google account. If you upload files to the service account’s drive you won’t see them in your Google Drive. It’s not a big problem because the uploaded files can be shared.

If for some reason you need to have files uploaded directly to your account you can’t use the service account. You will have to create a web application instead. That change the way how you authenticate. Web application requires a manual journey though OAuth. Backups usually work in background and there is no web interface for OAuth redirections. For that reason I prefer to use a private key.

Now when your API project is created you can download an example script I prepared for this post. It’s a command line utility in PHP which uploads a file to shared folder on Google Drive. It’s available on my GitHub account: cp2goole. For your convenience the script comes with Google API but don’t use it with your projects. Download the latest API with examples from the official page https://developers.google.com/drive/quickstart-php.

$ git clone https://github.com/lukaszkujawa/cp2google.git
$ cd cp2google/
$ vim cp2google.php

You will have to modify first lines of the script.

<?php

define( 'BACKUP_FOLDER', 'PHPBackups' );
define( 'SHARE_WITH_GOOGLE_EMAIL', '[email protected]' );

define( 'CLIENT_ID',  '700692987478.apps.googleusercontent.com' );
define( 'SERVICE_ACCOUNT_NAME', '[email protected]' );
define( 'KEY_PATH', '../866a0f5841d09660ac6d4ac50ced1847b921f811-privatekey.p12');

BACKUP_FOLDER – name of shared folder. The script will create it at the first run.
SHARE_WITH_GOOGLE_EMAIL – your google account.
CLIENT_ID – your project’s client id
SERVICE_ACCOUNT_NAME – your project’s account name. It’s called e-mail address on the console page.
KEY_PATH – path to the downloaded private key.

Replace those values to match your configuration. Save changes are run the file.

$ php cp2google.php README.md
Uploading README.md to Google Drive
Creating folder...
File: 0B9_ZqV369SiSM19KbTROWldqcFk created

Now check your Google Drive. You should find a new folder in the “Shared with me” section. You also should receive an e-mail saying that the file has been shared with you.

I won’t get though the code because it’s quite simple to understand. The only thing worth mentioning is that on Google Drive files and folders are the same thing. Folder has a specific mime type which is “application/vnd.google-apps.folder”.

Full documentation of Google Drive API can be found here https://developers.google.com/drive/v2/reference/. Most of the calls have an example in: JAVA, .NET, PHP, Python, Ruby, JavaScript, Go and Objective-C. It should be enough for most people😉

Google was always very generous when it comes down to storage. There are multiple ways to take advantage of that and backups are one of them. I wouldn’t use it to store business critical data but everything else should be just fine. It feels much more convenient then anything else.

7 thoughts on “Automated backups to Google Drive with PHP API

  1. Hi,
    awesome script! I’ve replaced my script with yours (which using private key). One question, how to ignore emails I get after uploading to GD?

    Email content was:
    I’ve shared an item with you.
    Item filename.txt

    Like

  2. This was very helpful, just what I needed, thanks a lot! Only had trouble with the fact that it needs PHP 5.3 or later, otherwise Drive API does not work because of some crypto algorithm limitations. Now I’m curios how much space does that “Service account” has. Is there a way to log into that account like I do in my personal account?

    Like

  3. Hi

    I am getting this error

    Fatal error: Class ‘finfo’ not found in

    Can you please help me out?

    Regards

    Like

  4. Hi,

    First of all, thanks for this great script, I’ve been using it for a year now. But now I’ve hit the wall: “The user has exceeded their Drive storage quota”.
    The script never quite worked as I expected: once every couple of days it would create the backup folder again, even though there already existed a folder with that name, and all new files were updated to that folder. After a couple of months there were many backup folders shared with me. I started to delete them (delete the folders, not each file). This might have been a bad idea.
    Anyway, now the script is not working at all, because the drive storage quota has been exceeded. Is there any solution to this? Is there a way for me to log into that account and clean it to free up space?

    Thanks

    Like

  5. Nice article but I was getting annoyed with the lack of images. Ran this as a snippet in Chromes Source pane of it’s inspector to recover them:

    Array.prototype.forEach.call(document.querySelectorAll(“.no-line”), function(el, i){
    var img = el.querySelector(“img”);
    img.setAttribute(“src”, el.getAttribute(“href”));
    img.setAttribute(“width”,”100%”);
    });

    Which might help someone else.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s