Adam
Adam

Reputation: 59

Uploading files to my Google Drive account using PHP

I'm aware that there are hundreds of posts covering variations of this topic, and I've spent the last few hours reading through them, but I just can't get this to work.

I'm wanting to upload files to my Google Drive account from my server using PHP via the Google Drive SDK (I'm using v2.2.0).

The script executes fine, it seems to be uploading somewhere and even returns a file id (always the same one though), but it's not showing in my Google Drive and I get the following message when I try and view the file:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "File not found: <FILE_ID>.",
    "locationType": "parameter",
    "location": "fileId"
   }
  ],
  "code": 404,
  "message": "File not found: <FILE_ID>."
 }
}

I've setup a service account and downloaded the JSON credentials. My aim is to create a function for uploading files stored on my server, so I don't require an oAuth consent screen.

Here's the test code so far:

<?php

    include_once __DIR__ . '/vendor/autoload.php';

    putenv('GOOGLE_APPLICATION_CREDENTIALS=../../../keys/MyProject-xxxxxxxxxxxx.json');

    $client = new Google_Client();
    $client->addScope(Google_Service_Drive::DRIVE);
    $client->useApplicationDefaultCredentials();
    $client->setApplicationName("MyApplication");
    $client->setScopes(['https://www.googleapis.com/auth/drive.file']);

    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents('cat.jpg');

    $service = new Google_Service_Drive($client);

    $createdFile = $service->files->create($file, array(
    'data' => $data,
    'mimeType' => 'image/jpeg',
    'uploadType' => 'multipart'));

    echo("<a href='https://www.googleapis.com/drive/v3/files/".$createdFile->id."?key=<MY_API_KEY>&alt=media' target='_blank'>Download</a>");

Upvotes: 0

Views: 618

Answers (1)

Adam
Adam

Reputation: 59

Solved!

You need to create a folder within Google Drive, then add the service account email address to the list of people who can add & edit.

Then you need to specify the folder id in your code:

$file->setParents(array("0B_xxxxxxxxxxxxxxxxxxxxxxxxx"));

Upvotes: 1

Related Questions