I'm trying to send test file to specific folder in my Google Drive account from CLI PHP script by using the public API key. I've generated the key and set my IP address in the Google dev console.
This is where i'm currently:
<?php
if (strtolower(PHP_SAPI) !== 'cli')
{
throw new Exception("Run this from CLI only");
}
$autoloader_path = '.' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR;
$autoloader_file = realpath($autoloader_path . 'autoload.php');
if (!file_exists($autoloader_file))
{
throw new Exception("Autoloader file not found");
}
require_once $autoloader_file;
if (!class_exists('\Composer\Autoload\ClassLoader', true))
{
throw new Exception("Composer autoloader failed to load");
}
$client = new Google_Client();
$client->setDeveloperKey('my-public-api-key');
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile($client);
$d = array(
'data' => file_get_contents("test.txt"),
'mimeType' => 'text/plain',
'uploadType' => 'media'
);
$result = $service->files->insert($file, $d);
var_dump($result);
I'm getting "Login required" error:
$ php backup.php
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media&key=**<my key>**: (401) Login Required' in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php:79
Stack trace:
#0 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Client.php(556): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Drive.php(1760): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /home/raspi/gdrive/backup.php(37): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 {main}
thr in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php on line 79
So how I can use the Public API key to send files or do I need to use OAuth? I've googled but only found OAuth file send examples.
composer.json
:
{
"name": "raspi/gdrive",
"description": "Gdrive",
"license": "BSD",
"require": {
"php": ">=5.4",
"google/apiclient": "1.0.*@beta"
}
}