arrow_back
Back

Google Drive API: files, uploads, permissions, and PHP examples

Andrew Dorokhov Andrew Dorokhov schedule 4 min read
menu_book Table of Contents

Creating a client object

To start working with API lets create a client object:

$client = new Google\Client();

Creating a service object

Make sure we have all the necessary scopes:

use Google\Service\Drive;

$client->addScope(Drive::DRIVE_READONLY);
$service = new Drive($client);

Now we can use any methods:

$files = $service->files->listFiles()->getFiles();
Method Description
files->listFiles Retrieves a list of files in the user’s Drive.
files->get Retrieves metadata for a specific file by its ID.
files->create Creates a new file in the user’s Drive.
files->update Updates metadata for a specific file.
files->copy Copies an existing file.
files->delete Permanently deletes a file.
files->emptyTrash Permanently deletes all files in the trash.
files->export Exports a Google Doc to a different format.
files->generateIds Generates a set of file IDs.
files->watch Sets up a notification channel for changes to a file.
about->get Retrieves information about the user’s Drive.
changes->listChanges Retrieves a list of changes to a user’s Drive.

Files

Each user has a “root” folder called “My Drive”. The user is the primary owner of this folder.

File types

File Type Description MIME Type
Blob A file that contains text or binary content such as images, videos, and PDFs. -
Folder A container you can use to organize other types of files on Drive. application/vnd.google-apps.folder
Shortcut A metadata-only file that points to another file on Drive. application/vnd.google-apps.shortcut
Third-party shortcut A metadata-only file that links to content stored on a third-party storage system. application/vnd.google-apps.drive-sdk
Google Workspace document A file that a Google Workspace application creates, such as Google Docs, Sheets, or Slides. application/vnd.google-apps.app (e.g., application/vnd.google-apps.spreadsheet for Google Sheets)

Get a list of files

$files = $service->files->listFiles()->getFiles();

foreach ($files as $file) {

    echo $file->getId() . '<br>';
    echo $file->getName() . '<br>';
}

Getting folders:

$query = "'$this->reports_folder_id' in parents 
    and mimeType='application/vnd.google-apps.folder'
    and name='Monthly CSV'";

$folders = $this->service->files->listFiles(['q' => $query]);

Creating a file

$folder_metadata = new DriveFile([
    'name'      => $new_folder_name,
    'mimeType'  => 'application/vnd.google-apps.folder',
    'parents'   => [$parent_folder_id] // Set the parent folder ID
]);

// Create the folder inside the parent folder
$folder = $service->files->create($folder_metadata);

// Output the ID of the newly created folder
echo 'Folder ID: ' . $folder->id;

Example:

/**
 * Get folder ID.
 *
 * If the folder doesn't exist, it will be created.
 *
 * @param $parent_id
 * @param $folder_name
 * @return string
 * @throws \Google\Service\Exception
 */
protected function get_folder_id( $parent_id, $folder_name ): string
{
    $query = "'$parent_id' in parents 
        and mimeType='application/vnd.google-apps.folder'
        and name='$folder_name'";

    $folders = $this->service->files->listFiles(['q' => $query]);

    if ( ! empty( $folders->getFiles() ) ) {

        return $folders->getFiles()[0]->getId();

    } else {

        $folder_metadata = new DriveFile([
            'name'      => $folder_name,
            'mimeType'  => 'application/vnd.google-apps.folder',
            'parents'   => [ $parent_id ]
        ]);

        $folder = $this->service->files->create( $folder_metadata );

        return $folder->id;
    }
}

Uploading a file

/**
 * Create a file metadata object.
 */
$file_metadata = new DriveFile([
    'name'		=> "$month.xlsx",
    'parents'	=> [ $year_folder_id ]
]);

$file = $this->service->files->create( $file_metadata, [
    'data'          => file_get_contents( $file_path ),
    'mimeType' 		=> mime_content_type( $file_path ),
    'uploadType'	=> 'multipart',
] );

return $file->getId();

Push notifications

Documentation: open_in_new Push notifications .

Three things you need to do:

  1. Register the domain of your receiving URL.
  2. Set up your receiving URL.
  3. Set up a notification channel for each resource endpoint you want to watch.

Whenever a channel’s resource changes, the Drive API sends a notification message as a POST request to that URL.

1. Register your domain

  1. Open the open_in_new Domain verification page in the API Console.
  2. Click Add domain.
  3. Fill in the form and click Add domain again.

You can then use any of those domains to receive push notifications.

2. Creating a notification channel

Each notification channel is tied to both a particular user (or service account) and a particular resource. A watch request fails unless the current identity owns or can access that resource.

<?php

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

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/service-account.json');

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Drive::DRIVE);

$service = new Google_Service_Drive($client);

$channel = new Google_Service_Drive_Channel();
$channel->setId('4ba78bf0-6a47-11e2-bcfd-0800200c9a77');
$channel->setType('web_hook');
$channel->setAddress('https://dorohoff.net/push-notification.php');

try {
    $result = $service->files->watch('1NLuJl34YwKCgSx2OLMRB9jBD5BPZvXYHchdHKBBKHHo', $channel);
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

YouTube Data API: channels, videos, playlists, and quotas

arrow_forward