Undefined variable when Uploading a file to Google Drive - php

Hi i have an issue when i call Google Drive API using the PHP Client Library.
my coding is
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$result = $service->files->insert($file, array(
'data' => file_get_contents("dd.doc"),
'mimeType' => 'text/plain',
'uploadType' => 'multipart'
));
I got the following errors
Undefined variable: service Trying to get property of non-object
Call to a member function insert()

Did you include the client lib in your script? or did you just forget to add that part?
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
Also check that $service was created properly. you are missing that code.
$client_id = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';
$redirect_uri = '<YOUR_REDIRECT_URI>';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
A very good example can be found here

Related

Undefined type 'Google_Service_Oauth2' intelephense(1009) PHP

I currently modify my php script using namespace. I've done with the scripts but there are problem with Google API package
// create Client Request to access Google API
$client = new \Google_Client(); => THIS ONE WORKS
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
$accessToken = $key;
// Get $id_token via HTTPS POST.
try{
$arrToken = $client->setAccessToken($accessToken);
// get profile info
$google_oauth = new \Google_Service_Oauth2($client); => IT DOESNT
$google_account_info = $google_oauth->userinfo->get();
$checkEmail = $google_account_info->email;
$name = $google_account_info->name;
$googleId = $google_account_info->id;
}
Here is the error
Undefined type 'Google_Service_Oauth2' intelephense(1009)
If I do not use namespace, it has no problem. This one really weird.

How to connect to a Google Drive API and get the AccessToken

I'm here with a little problem to connect my script with a Google Drive API using a credentials json file.
This is my code:
$oauth_credentials = __DIR__.'\credentials.json';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google\Client();
$client->setAccessType('offline');
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
var_dump($token);
}
Obviously I used composer to add google apiclient project to my script, and I used the cloud console of google to enable Drive API and create the credentials for this, and I used the credentials.json file downloaded of Google Console.
All is apparently good, I added a test account and used this account to accept permissions to use the Drive API.
Using the playground, in this URL https://developers.google.com/oauthplayground I test my credentials and I get the authorization code to create a refresh token and access token, but when i use this authorization code in my script the result is this: ""
'error' => string 'invalid_grant' (length=13)
'error_description' => string 'Bad Request' (length=11)
Any suggests? this code is exactly like the code appear in the Google examples.
My problem is that the focus is wrong way, I create a service account and generate the json credentials file and I use this code for upload a file:
putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/drive.file']);
try {
$service = new Google_Service_Drive($client);
$file_path = 'example.txt';
$file = new Google_Service_Drive_DriveFile();
$file->setName('example.txt');
$file->setParents([$this->folder_id]);
$file->setDescription('Example description text');
$result = $service->files->create($file,[
'data' => file_get_contents($file_path),
'mimeType' => 'text/plain',
'uploadType' => 'text'
]);
echo 'Link to the uploaded file';
}
catch(Google_Service_Exception $gs)
{
$m = json_decode($gs->getMessage());
echo $m->error->message;
}
catch(Exception $e)
{
echo $e->getMessage();
}

Google API 2.0 PHP Server to Server cannot upload file to Google Drive

I am trying to upload image from my website to my Google Drive using Google API 2.0 (PHP Version). When I tried the code below, no error reported on the webpage but my photo wasn't being uploaded. Can some one please help me with problem? I apprecitated about it.
require_once realpath('vendor/autoload.php');
$client = new Google_Client();
$client->setAuthConfig('vendor/MyProject.json');
$client->useApplicationDefaultCredentials();
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
// This is uploading a file directly, with no metadata associated.
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->create(
$file,
array(
'data' => file_get_contents('1.jpeg'),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
)
);
?>

How to convert RTF document to Google Document?

I have got Google's sample code working with an RTF file my application has created. How can this RTF document be converted to a Google Document?
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xxxxxx');
$client->setClientSecret('xxxxxx');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('5.25.14-M02000-Ramin');
$file->setDescription('A test document');
$file->setMimeType('application/rtf');
$data = file_get_contents('5.25.14-M02000-Ramin.rtf');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/rtf',
));
print_r($createdFile);
?>
You need to send an optional parameter with your request.
convert boolean
Whether to convert this file to the corresponding Google Docs format. (Default: false)
Something like this maybe, but I'm not sure your code is using the old Google API PHP client Lib.
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/rtf',
'convert' => 'true'
));
Note: Yes I know you are following Files: insert example but unfortunately that uses the old Client lib. I have been told they are in the process of updating it. The new Google API PHP client lib can be found on GitHub. There is a file upload example there as well but its very basic. Fileupload.php and doesn't include the convert parameter either.

"PHP Fatal error: Call to a member function setTitle() on a non-object" in Google Drive php UPDATE script

I'm using this php script to INSERT (upload) a file to my Google Drive, and its perfect:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX');
$drive->setClientSecret('YYY');
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test');
$doc->setDescription('Test Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('test.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
Now I want to UPDATE (not upload) my existing Google Drive file, and I'm using this script:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX');
$drive->setClientSecret('YYY');
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$drive->setAccessToken(file_get_contents('token.json'));
$fileId = "ZZZ";
$doc = $gdrive->files->get($fileId);
$doc->setTitle('Test'); // HERE I GET THE ERROR "CALL TO A MEMBER FUNCTION SETTITLE()..."
$doc->setDescription('Test Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('test.txt');
$output = $gdrive->files->update($fileId, $doc, array(
'newRevision' => $newRevision,
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
Unluckly I get this error:
PHP Fatal error: Call to a member function setTitle() on a non-object in line $doc->setTitle...
I have followed THIS reference. Please can u help me to resolve the issue, or can you suggest the precise and right code to UPDATE a file to Google Drive through php? Thanks!
You are expecting $doc to be an object, which it is not because the Google client libraries are configured to return data arrays instead of objects by default.
To change this behavior without modifying the original source you can add a local_config.php file next to the existing config.php that has these contents:
<?php
$apiConfig = array(
'use_objects' => true,
);
The client libraries will detect and use this configuration automatically.

Categories