Down you can see my code and it uploads files to my google drive. Now I am trying to use service account to let the people to upload files to my Google drive without their google accounts (Visitors will submit html form with their file and my app will upload that file to my drive ). But I am stuck with it. Can not find even just one working example. Any ideas?
$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);
// store in the session also
$_SESSION['upload_token'] = $token;
// redirect back to the example
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
$authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
// We'll setup an empty 1MB file to upload.
DEFINE("TESTFILE", 'test.jpg');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
// This is uploading a file directly, with no metadata associated.
$file = new Google\Service\Drive\DriveFile();
$service = new Google_Service_Drive($client);
$file->setName("Hello World!");
$result = $service->files->create(
$file,
[
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
]
);
$permissionService = new Google_Service_Drive_Permission();
$permissionService->role = "reader";
$permissionService->type = "anyone"; // anyone with the link can view the file
$service->permissions->create($result->id, $permissionService);
The following code will show you how to set up service account authorization.
Remember though the files will be uploaded to the service accounts drive account. If you want them uploaded to your personal drive account. You need to share a directory on your drive account with the service account. You do that though the web app like you would any other user, using the service account email address. Its the property that looks like an email.
You should just be able to remove the auth you have now and then use this. You will however need set the parents in the upload metadata to be that of that directory you want the fill uploaded to.
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::DRIVE)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(array(Google_Service_Analytics::DRIVE));
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Doing something like this will then get you the same service object.
$service = new Google_Service_Drive(getGoogleClient());
Related
I am able to get file name of google doc using drive-api-php but I am unable to get file content in a php variable. provide me working code to get content of google doc file in a php variable. I checked api reference page but unable to understand how to use code. Not clear methos are given for php.
<?php
require __DIR__ . '/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
echo 'Log in here';
//print 'Enter verification code: ';
$authCode = $_GET['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$fileId = "1jNCyWDaCq4KrUo3u3HolqQKysv2P5423KErpvHQNjn0";
$file = $service->files->get($fileId);
echo "File name: ".$file->getName(); //Working
echo "MIME type: " . $file->getMimeType(); //Working
$a = $service->files->getContent(); //Not Working provide code
echo "File Content: ".$a;
?>
Get contents of a google doc using the google drive api.
Answer to your question is you cant.
You need to remember that the Google Drive api is a file storage api it can help you upload, download and list files stored in google drive. It does not give you any access to edit the files stored with in Google drive.
download file from google drive to your hard drive.
The file should be within the body but it depends upon the file type you are after if its a google doc then you will need to use file export and not file get.
Something like the following should export a google doc file to a microsof docx file and save it to your harddrive.
$file = $service->files->export($fileId, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', array(
'alt' => 'media' ));
$size = $file->getBody()->getSize();
if($size > 0) {
$content = $file->getBody()->read($size);
}
Edit the contents of a google drive document
In order to edit the contents of a google document you would need to use the google Doc api. Just remember the google doc api gives you the ability to edit the document programmatically. If you want to be able to display the contents of google documents nicely on your website your going to have to do all the formatting and display yourself.
I am currently using the Google Calendar API for a web application. However, every hour, I am prompted with a link to verify quickstart access. Does anyone know how to fix this?
Details:
I have created a new gmail id: redu#gmail.com
redu#gmail.com has an associated calendar
My php based web application needs to do the following with calendar:
Create a new calendar for every registered user (as an additional calendar for redu#gmail.com)
Create an event for a logged in user and add another registered user as an invitee
I have tried using OAUTH and service accounts with no luck. Any help is greatly appreciated.
Below is the code that creates Google_Client and Srvice objects using service account's credentials
function __construct()
{
Service account based client creation.
$this->client = new Google_Client();
$this->client->setApplicationName("Redu");
$this->client->setAuthConfig(CREDENTIALS_PATH);
$this->client->setScopes([SCOPES]);
$this->client->setSubject('redu#gmail.com');
$this->client->setAccessType('offline');
$this->service = new Google_Service_Calendar($this->client);
}
When I try to use the $service object to create a calendar or create an event I get an error saying that domain wide permissions are not setup. However, when I created the service account I did enable domain wide delegation.
EDIT:
Below is my code to create a Google_Client using service account key and use the client to create a new calendar for redu#gmail.com. Note that I shared redu#gmail.com's calendar with reduservice#subtle-breaker-280602.iam.gserviceaccount.com and set the permission to "Manage Changes and Manage Sharing". The error I am getting is below the code:
require (__DIR__.'/../../../vendor/autoload.php');
define('CREDENTIALS_PATH', __DIR__ . '/redu_service_account_credentials.json');
define('SCOPES', Google_Service_Calendar::CALENDAR);
function createNewCalendar($userName) {
//Service account based client creation.
$client = new Google_Client();
$client->setApplicationName("REdu");
// path to the credentials file obtained upon creating key for service account
$client->setAuthConfig(CREDENTIALS_PATH);
$client->setScopes([SCOPES]);
$client->setSubject('redu#gmail.com');
$client->setAccessType('offline');
$service = new Google_Service_Calendar($client);
$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary($userName);
$calendar->setTimeZone('America/Los_Angeles');
$createdCalendar = $service->calendars->insert($calendar);
// Make the newly created calendar public
$rule = new Google_Service_Calendar_AclRule();
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType("default");
$scope->setValue("");
$rule->setScope($scope);
$rule->setRole("reader");
// Make the calendar public
$createdRule = $service->acl->insert($createdCalendar->getId(), $rule);
return $createdCalendar->getId();
}
ERROR:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
}'
OAUTH2 vs Service accounts
Oauth2 and service accounts are two different things. You use oauth2 if you are trying to access a users data. The consent window you mentioned will prop up and ask that they grant permission for your application to access their data.
Service accounts on the other hand are dummy users who can be pre approved to access data you the developer control. You could share a calendar with a service account granting it access to that calendar it will no need to be authenticated in the same manner as a user.
A service account will never popup and request access again.
Oauth2 example with refresh token.
The issue is that your access token is expiring. If it expires then the user will need to grant your application access to their data again. To avoid this we use a refresh token and store that in a session varable and when the acces stoken expires we just request a new one.
Notice how i am requesting $client->setAccessType("offline"); this will give me a refresh token.
the session vars are now set storing this data
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
Then latter i can check if the access token is expired if so i refresh it
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
oauth2callback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Authentication.php
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* #return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* #return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
code for service account
The credential files are different dont mix them up.
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Error
Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
There are two types of clients Oauth2 clients and Service account clients. The .json file you download is diffrent for each client. As is the code you will use for each client. You cant interchange this code.
The error you are getting stats that the client you are using cant be used for the code you are using. Try to download the client secret .json for the service account again.,
Here's a working example that generates the authentication object using the Service Account's JSON file
$client = new Google\Client();
$client->setApplicationName(APP_NAME);
$client->setAuthConfig(PATH_TO_JSON_FILE);
$client->setScopes(['YOUR_SCOPE1','YOUR_SCOPE2']);
$client->setSubject(EMAIL_OF_PERSON_YOURE_IMPERSONATING);
$client->setAccessType('offline');
$service = new Google_Service_Drive($client);
// Do stuff with the $service object
Generate Service Account in Google API Console
Delegate domain wide authority to that Service Account's Client ID in Google workspace and define the scopes that the Service Account will have access to
Use the code above and make sure to include one more more relevant scopes
I'm implementing google drive api to implement in my application. I did that all code configuration from google-drive-client-php documentation. But I got an this permission error. Please give me any hint for this:
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline");
$client->setScopes("https://www.googleapis.com/auth/drive");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
$fileMetaData = new Google_Service_Drive_DriveFile(array(
'name' => 'RootFolder',
'mimeType' => 'application/vnd.google-apps.folder'));
$parentFolder = $drive->files->create($fileMetaData, array(
'fields' => 'id'
));
$permission = new Google_Service_Drive_Permission();
$permission->setValue('me');
$permission->setType('anyone');
$permission->setRole('writer');
$drive->permissions->insert($parentFolder->getId(), $permission);
echo "<pre>";
echo json_encode($parentFolder);
} else {
$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Thank u :)
so you are requesting ...
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
while you actually might require ...
$client->addScope(Google_Service_Drive::DRIVE);
for reference, here's the mapping of the API scopes:
/** View and manage the files in your Google Drive. */
const DRIVE = "https://www.googleapis.com/auth/drive";
/** View and manage its own configuration data in your Google Drive. */
const DRIVE_APPDATA = "https://www.googleapis.com/auth/drive.appdata";
/** View and manage Google Drive files and folders that you have opened or created with this app. */
const DRIVE_FILE = "https://www.googleapis.com/auth/drive.file";
/** View and manage metadata of files in your Google Drive. */
const DRIVE_METADATA = "https://www.googleapis.com/auth/drive.metadata";
/** View metadata for files in your Google Drive. */
const DRIVE_METADATA_READONLY = "https://www.googleapis.com/auth/drive.metadata.readonly";
/** View the photos, videos and albums in your Google Photos. */
const DRIVE_PHOTOS_READONLY = "https://www.googleapis.com/auth/drive.photos.readonly";
/** View the files in your Google Drive. */
const DRIVE_READONLY = "https://www.googleapis.com/auth/drive.readonly";
/** Modify your Google Apps Script scripts' behavior. */
const DRIVE_SCRIPTS = "https://www.googleapis.com/auth/drive.scripts";
I got an solution for my problem
Remove
$permission->setValue('me');
and change this Permission method to
$drive->permissions->insert($parentFolder->getId(), $permission);
To
$drive->files->create($fileMetaData, array('fields' => 'id'));
Here in the google drive api insert an setValue() method is deprecated so it was not work.
I want to upload files to Google Drive using the API, but I need to do this using a cron job (autobackup of webfiles+sql to Google drive).
That means (I suppose) that I need to authenticate using something else than the user interaction method.
The example that I have been using: https://developers.google.com/api-client-library/php/auth/web-app to get me going, and its working with user authenticating.
I would appreciate some tips on how to do this without user interaction, so it can run on a cronjob.
Here are the PHP code for authenticate and upload file (working example with manual user auth and single file upload)
<?php
require_once 'google-api-php-client/vendor/autoload.php';
/* Config */
$servername = 'content here';
$redirect_uri = 'https://example.com/';
$client = new Google_Client();
$client->setAuthConfig('client_manual_authentiation.json');
$client->addScope(Google_Service_Drive::DRIVE);
if(isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
foreach($drive->files->listFiles(array("q" => "name = '{$servername}'"))->getFiles() as $key => $element){
if($element->name == $servername){
//create todays folder on Google Drive
$today_folder_meta = new Google_Service_Drive_DriveFile(array(
'name' => 'myfile.txt',
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => array($element['id'])
));
$today_folder = $drive->files->create($today_folder_meta, array(
'fields' => 'id'
));
}
}
}else{
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
To do this, you want to create a Google OAuth2 Service Account. You can then download a set of JSON credentials that your app will use to authenticate without user interaction.
This is described in the following article:
Using OAuth 2.0 for Server to Server Applications
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
You will then be able to download credentials like the following to use in your app:
{
"type":"service_account",
"project_id":"your-project-id",
"private_key_id":"deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
"private_key":"-----BEGIN PRIVATE KEY-----\nMIIEv...4XIk=\n-----END PRIVATE KEY-----\n",
"client_email":"foobar#bazqux.iam.gserviceaccount.com",
"client_id":"12345678901234567890",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/foobar%40bazqux.iam.gserviceaccount.com"
}
Here is a Google PHP example of how to use this:
https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
You can create the Service Account in the Google API Console as shown here:
Hi guys i'm trying uploading file trought G drive API.
Can't find out why it returns error:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Gdrive{
function initialize(){
$credentials = $this->GetOAuth2Credentials($_GET['code']);
$_SESSION['credentials'] = $credentials;
}
/**
* Exchange an authorization code for OAuth 2.0 credentials.
*
* #param String $authorizationCode Authorization code to exchange for an
* access token and refresh token. The refresh token is only returned by
* Google on the very first exchange- when a user explicitly approves
* the authorization request.
* #return OauthCredentials OAuth 2.0 credentials object
*/
function GetOAuth2Credentials($authorizationCode) {
$client = new apiClient();
$client->setClientId(Config::5112+++++.apps.****5971157#developer.gserviceaccount.com);
$client->setRedirectUri(Config::site_url());
/**
* Ordinarily we wouldn't set the $_GET variable. However, the API library's
* authenticate() function looks for authorization code in the query string,
* so we want to make sure it is set to the correct value passed into the
* function arguments.
*/
$_GET['code'] = $authorizationCode;
$jsonCredentials = json_decode($client->authenticate());
$oauthCredentials = new OauthCredentials(
$jsonCredentials->access_token,
isset($jsonCredentials->refresh_token)?($jsonCredentials->refresh_token):null,
$jsonCredentials->created,
$jsonCredentials->expires_in,
Config::CLIENT_ID,
Config::CLIENT_SECRET
);
return $oauthCredentials;
}
function SaveNewFile($inputFile) {
try {
$mimeType = 'text/plain';
$file = new Google_DriveFile();
$file->setTitle($inputFile->title);
$file->setDescription($inputFile->description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($inputFile->parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($inputFile->parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
$createdFile = $this->service->files->insert($file, array(
'data' => $inputFile->content,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error saving new file to Drive: ' . $e->getMessage(), 0);
throw $e;
}
}
}
when i invoke the initialize() method it returns error:
Message: Undefined index: code
Fatal error: Class 'apiClient' not found
what should be? i'm doing right in my code ? does i need more code to make it works? i created web application project on google api console.
need i to include google php sdk? in the google docs it is not mentioned for google drive api :/
You are probably using an older version of the PHP client library. Make sure you have the latest source and follow the instructions in the Google Drive SDK quickstart page to learn how to write a complete PHP app to upload a file to Drive:
https://developers.google.com/drive/quickstart
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();
please use those require files and Google_Client().