PHP

Listing and uploading files with the Google Drive API in PHP

Authenticate with a service account, then list and create files from your server.

sf
Naoki « segfault »
systèmes & back-end · updated Jan 2025
This guide revisits and updates an original tutorial from noiretaya.com (log.noiretaya.com/193, /262). The code has been refreshed for current versions.

Install the client

composer require google/apiclient

Authenticate

For server-to-server access, use a service account JSON key and grant it access to the target folder.

require 'vendor/autoload.php';
$client = new Google\Client();
$client->setAuthConfig('service-account.json');
$client->addScope(Google\Service\Drive::DRIVE);
$drive = new Google\Service\Drive($client);

List files

$files = $drive->files->listFiles([
  'pageSize' => 20,
  'fields'   => 'files(id, name, mimeType)'
]);
foreach ($files->getFiles() as $f) {
  echo $f->getName() . ' — ' . $f->getId() . PHP_EOL;
}

Upload a file

$meta = new Google\Service\Drive\DriveFile(['name' => 'report.pdf']);
$drive->files->create($meta, [
  'data'       => file_get_contents('report.pdf'),
  'mimeType'   => 'application/pdf',
  'uploadType' => 'multipart',
  'fields'     => 'id'
]);
Heads-up: service accounts have their own Drive storage. To upload into your Drive, share the destination folder with the service-account e-mail and pass its folder id in parents.