Dorokhov.codes

4. Service: Google Drive

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();