How to Upload Files to Google Drive Using PHP API Client

I’m working on a PHP script that needs to upload files from my server to Google Drive. I’ve been following the Google Drive API documentation but I keep running into authentication issues.

Here’s what I have so far:

<?php
require_once 'vendor/autoload.php';

$googleClient = new Google_Client();
$googleClient->setScopes(['https://www.googleapis.com/auth/drive']);
$googleClient->setClientId('your-client-id-here');
$googleClient->setClientSecret('your-client-secret-here');
$googleClient->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');

$driveService = new Google_Service_Drive($googleClient);

$fileContent = file_get_contents('photo.png');

try {
    $driveFile = new Google_Service_Drive_DriveFile();
    $driveFile->setName('uploaded_' + time() + '.png');
    
    $result = $driveService->files->create($driveFile, array(
        'data' => $fileContent,
        'mimeType' => 'image/png',
        'uploadType' => 'multipart'
    ));
    
    echo 'File uploaded successfully: ' + $result->getId();
} catch (Exception $error) {
    echo 'Upload failed: ' + $error->getMessage();
}
?>

I get this error message: fopen(compress.zlib://https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart) failed to open stream

I think the problem is with OAuth authentication but I’m not sure how to fix it. Has anyone successfully implemented file uploads to Google Drive with PHP? What am I missing in my setup?

Your main problem is the authentication flow. You’re not handling the OAuth token exchange properly before hitting the API. Ensure you’ve set up your client credentials correctly, redirect users to Google’s auth URL, and then swap the authorization code for an access token. It’s important to store the refresh token for automated uploads. Additionally, your file upload parameters are inaccurate. Use ‘uploadType’ => ‘media’ for simple uploads or consider resumable uploads for larger files. The compress.zlib error indicates the client isn’t authenticated; make sure to obtain a valid access token first. If you’re performing server-to-server interactions, consider using service account authentication.

yeah, fix the oauth token first! also, php uses . for concatenation, not +. that’s probably what’s breaking it. check your token retrieval process too!

Been there, done that - multiple times. Google Drive’s PHP SDK is a nightmare because of OAuth complexity.

Skip the token headaches entirely. I use Latenode to automate this - it watches server folders and uploads files to Drive without touching PHP code.

Latenode handles OAuth automatically. Connect your Google Drive once, forget about it. No more token refresh failures or auth errors.

I built our backup system this way. Files upload automatically, organized by type or date. 10 minutes setup vs hours debugging PHP libraries.

Trigger uploads via webhook from PHP, or use file monitoring. Much cleaner than wrestling with Google’s client libraries.