Upload file to google drive issue PHP


I have a problem while uploading a file to Google Drive, I can't upload file. Anyone can help, please answer.

Hereunder is the error I got while uploading file:

 "error": {
  "errors": [
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
  "code": 401,
  "message": "Invalid Credentials"

I have registered the application with the drive SDK and I am using the drive SDK client ID. Also I am using the updated access token everytime from the long-lived refresh token saved in DB.

The code is here:

$fname = basename($updfile); // where $updfile is the file name with path
$turl = "https://www.googleapis.com/drive/v1/files";
$jsondata = '
    "title": "'.$fname.'",
    "description":"The mailchimp data export to google drive."

$headers = 'Host: www.googleapis.com'."\r\n";
$headers .= 'Authorization: Bearer '.$access_token."\r\n";  // $access_token is token generating everytime from refresh token
$headers .= 'Content-Type: application/json'."\r\n";
$headers .='Content-Length: '.strlen($jsondata)."\r\n";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $turl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsondata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($headers));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Please revert/answer, if anyone have the solution or suggestion regarding this. Thanks in Advance.


I'd recommend using the PHP client library and checking the documentation for a PHP snippet showing how to upload a file to Google Drive:


If for any reasons you want to keep using php_curl and manually construct the HTTP request, you should try sending the same request with the OAuth 2.0 Playground and compare it with yours.

Why not try to use your access token in a rest client to see if the problem comes from your PHP code or your access token.

Postman Rest Client for Chrome is very simple to use.

I think your url is incorrect:

$turl = "https://www.googleapis.com/drive/v1/files";

It should be:

$turl = "https://www.googleapis.com/upload/drive/v1/files";

Here are the docs (as thin as they are) on using the v2 upload features. It may or may not be more useful than using v1 :)


This video can help you solving your question :)
By: admin