Search code examples
phpgoogle-drive-api

How to properly upload file to Google Drive via curl PHP


I am trying to upload files to Google Drive via curl in PHP leveraging this API sample: Google Drive File Upload API.

Here is my issue:

When I run the code below. I got a successful message as per below but no file is uploaded to that folder.

Here is the Google API Response

string(121) "{ "kind": "drive#file", "id": "171bgh8-nDojxGjd_Fxxxxxxx", "name": "Untitled", "mimeType": "image/png" } " 

Here is the code

$file_path = 'baby.png';
$folder_id = 'id of the folder goes here'; // ID of the folder you want to upload to

$mimetype=  mime_content_type($file_path);
$filename=  basename($file_path);


$headers = array(
"Authorization: Bearer $access_token",
"Content-Type: $mimetype"
);


$post_fields = json_encode(array(
'name' => basename($file_path),
'parents' => array($folder_id),
'metadata' => "{name :$filename};type=application/json;charset=UTF-8",
 'file' => new CURLFile($file_path, $mimetype),
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

How do I get the file uploaded to that folder via folder ID?


Solution

  • I am not sure what is the reason from re-inventing the wheal.

    Google already provides an SDK for that purpose

    first install it using composer

    composer require google/apiclient
    

    After that you could try something like that

    use Google\Client;
    use Google\Service\Drive;
    # TODO - PHP client currently chokes on fetching start page token
    function uploadBasic()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $fileMetadata = new Drive\DriveFile(array(
            'name' => 'photo.jpg'));
            $content = file_get_contents('../files/photo.jpg');
            $file = $driveService->files->create($fileMetadata, array(
                'data' => $content,
                'mimeType' => 'image/jpeg',
                'uploadType' => 'multipart',
                'fields' => 'id'));
            printf("File ID: %s\n", $file->id);
            return $file->id;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        } 
    
    }
    

    You could check the docs here