$client->useApplicationDefaultCredentials(); $client->addScope(Google_Service_Drive::DRIVE); 4.1 Listing Files
// Save refresh token for future use if (!isset($accessToken['refresh_token'])) // Handle missing refresh token (may require revoking previous tokens) google drive api php
require_once 'vendor/autoload.php'; $client = new Google\Client(); $client->setApplicationName('Drive API PHP Demo'); $client->setScopes(Google_Service_Drive::DRIVE_FILE); $client->setAuthConfig('credentials.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); 3.1 OAuth 2.0 for Installed/Web Apps The system must obtain and refresh tokens programmatically: $client = new Google\Client()
while (!$media->getResumeUri()) $status = $media->nextChunk(); setApplicationName('Drive API PHP Demo')
if ($client->isAccessTokenExpired()) $refreshToken = $client->getRefreshToken(); $client->fetchAccessTokenWithRefreshToken($refreshToken); // Persist new token
$fileMetadata = new Google_Service_Drive_DriveFile([ 'name' => 'report.pdf', 'parents' => ['root'] ]); $content = file_get_contents('/local/path/report.pdf'); $file = $service->files->create($fileMetadata, [ 'data' => $content, 'uploadType' => 'multipart', 'fields' => 'id' ]);
$chunkSize = 256 * 1024; // 256KB per chunk $client->setDefer(true); $request = $service->files->create($fileMetadata); $media = new Google_Http_MediaFileUpload( $client, $request, 'application/pdf', fopen('/path/largefile.pdf', 'r'), true, $chunkSize );