PHP Classes
elePHPant
Icontem

Google drive api $parameters usage

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us

      PHP OAuth API  >  PHP OAuth API package blog  >  Painless OAuth with PHP  >  All threads  >  Google drive api $parameters usage  >  (Un) Subscribe thread alerts  
Subject:Google drive api $parameters usage
Summary:Not able to configure drive api parameters to upload a file
Messages:12
Author:Byju Chalad
Date:2014-04-28 13:10:42
Update:2014-05-14 22:44:28
 
  1 - 10   11 - 12  

  1. Google drive api $parameters usage   Reply   Report abuse  
Picture of Byju Chalad Byju Chalad - 2014-04-28 13:10:43
Dear Manuel Lemos,
I am not able to configure drive api parameters to upload selected file. Using mysqli_login_with_google.php. My offline token is getting authenticated every time without any problem. But while uploading the file it is created in my drive as untitled and the content is empty.

My code is given below.

------------------------------------------------------


<?php


require('http.php');
require('oauth_client.php');
require('database_oauth_client.php');
require('mysqli_oauth_client.php');

//this is for including database variables
include('../config.php');


$client = new mysqli_oauth_client_class;


$client->database = array(
'host'=>$dbhost,
'user'=>'hfroot',
'password'=>$dbpasswd,
'name'=>'hf',
'port'=>$dbport,
'socket'=>'/var/lib/mysql/mysql.sock'
);
$client->server = 'Google';

/*
* Set the offline access only if you need to call an API
* when the user is not present and the token may expire
*/
$client->offline = true;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].
dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/test4.php';

$client->client_id = 'xxxxxxxxxxxxx.apps.googleusercontent.com'; $application_line = __LINE__;
$client->client_secret = 'SyB0xxxxxxxxxxxxxxxxx_P';

if(strlen($client->client_id) == 0
|| strlen($client->client_secret) == 0)
die('Please go to Google APIs console page '.
'http://code.google.com/apis/console in the API access tab, '.
'create a new client ID, and in the line '.$application_line.
' set the client_id to Client ID and client_secret with Client Secret. '.
'The callback URL must be '.$client->redirect_uri.' but make sure '.
'the domain is valid and can be resolved by a public DNS.');

/* API permissions
*/
$client->scope = 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile '.'https://www.googleapis.com/auth/drive';
$client->user = 1;

if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;

}
elseif(strlen($client->access_token))
{

$parameters = array(
'Content-Type:'=>$_FILES["file"]["type"],
'title:'=>$_FILES["file"]["name"],
'Content-Length:' => $_FILES["file"]["size"],
'Authorization:' => "Bearer ".$client->access_token,
'data:'=>$data,
);
/* $success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo',
'GET', array(), array('FailOnAccessError'=>true), $user); */

/*
* Once you were able to access the user account using the API
* you should associate the current OAuth access token a specific
* user, so you can call the API without the user presence, just
* specifying the user id in your database.
*
* In this example the user id is 1 . Your application should
* determine the right user is to associate.
*/
if($success)
{
$success = $client->SetUser(1);
echo '<form action="test4.php" method="post"';
echo 'enctype="multipart/form-data">';
echo '<label for="file">Filename:</label>';
echo '<input type="file" name="file" id="file"><br>';
echo '<input type="submit" name="submit" value="Submit"> ';
echo '</form>';

if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
//$gclient=$client;
if ($_FILES["file"]["name"]!="")
{

$data = file_get_contents($_FILES["file"]["tmp_name"]);
$success = $client->CallAPI('https://www.googleapis.com/upload/drive/v2/files',
'POST',$parameters,array('FailOnAccessError'=>true, 'RequestContentType'=>$_FILES["file"]["type"]), $user);

}

}

echo 'Finished service Configuration';
}



}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Google OAuth client results</title>
</head>
<body>
<?php
echo '<h1>', HtmlSpecialChars($user->name),
' you have logged in successfully with Google!</h1>';
echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
?>
</body>
</html>
<?php
}
else
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php
}

?>



----------------------------------------------
My another question is

Is it possible to pass authenticated token to Google_Client.php and Google_DriveService.php from google for accessing google api's?
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
elseif(strlen($client->access_token))
{
$gclient=$client;
$serv=new Google_DriveService($gclient);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $serv->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',));

}
}
}



  2. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2014-04-29 01:22:06 - In reply to message 1 from Byju Chalad
There was a small bug that prevented sending requests of custom content types. The problem is fixed in the latest version. Try it with this code and let me know if you still have problems.

$file_name = 'http://files.phpclasses.org/graphics/phpclasses/elephpant.png';
$content_type = 'image/png';
$data = file_get_contents($file_name);
$parameters = array();
$success = $client->CallAPI(
'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
'POST', $parameters, array('FailOnAccessError'=>true,
'RequestContentType'=>$content_type, 'RequestBody'=>$data), $upload);

  3. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Byju Chalad Byju Chalad - 2014-04-29 14:37:06 - In reply to message 2 from Manuel Lemos
Dear Manuel Lemos,

I really appreciate your quick reply means i am frustratedly waiting for your reply. The code you suggested is not changing the situation. The file name Untitled creating on the drive without the content. And Mime type it sis creating is Mime type: application/octet-stream and size is Size: 0 bytes.

  4. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2014-04-29 17:23:19 - In reply to message 3 from Byju Chalad
That is because you also need to download the latest version of the class that fixed a problem that was causing that situation.

  5. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Byju Chalad Byju Chalad - 2014-04-30 03:34:40 - In reply to message 4 from Manuel Lemos
Dear Manuel,

The response I loved it. Thank you for the help you extended. The patch you suggested is perfectly working. If you have some more time to assist me kindly show me how to add file name (title) in the passing parameter. And please tell me how the code framed according to the Google POST documentation of simple upload.


as per google documentation below is the POST format for simple upload
-------------------------------------------------------------------------
POST /upload/drive/v2/files?uploadType=media HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Content-Length: number_of_bytes_in_JPEG_file
Authorization: Bearer your_auth_token

JPEG data
-------------------------------------------------------------------------
and for putting filename google documentation says
------------------------------------------------------------------------
HTTP/1.1 200
Content-Type: application/json

{
"title": "My File"
}
------------------------------------------------------------------------
How this can be converted into url parameters structure of your class.


Again with a warm hug and thank your for your help

Byju

  6. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2014-05-01 18:02:43 - In reply to message 5 from Byju Chalad
You can compose request that submits the file and attributes in a multipart container as you mentioned, but it may be simpler to send a separate request to set the attributes after the file is uploaded. It would look like this:

$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo',
'GET', array(), array('FailOnAccessError'=>true), $user);
$file_name = 'http://files.phpclasses.org/graphics/phpclasses/elephpant.png';
$content_type = 'image/png';
$data = file_get_contents($file_name);
$parameters = array();
$success = $client->CallAPI(
'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
'POST', $parameters, array('FailOnAccessError'=>true, 'RequestContentType'=>$content_type, 'RequestBody'=>$data), $upload);
if($success)
{
$parameters = new stdClass;
$parameters->title = 'elephpant.png';
$success = $client->CallAPI(
'https://www.googleapis.com/drive/v2/files/'.$upload->id,
'PUT', $parameters,
array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $upload);
}

  7. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Byju Chalad Byju Chalad - 2014-05-05 18:34:47 - In reply to message 6 from Manuel Lemos
Dear Manuel Lemos,
Finally after a long trial and error i found a solution for my requirement. Oauth with a single user by refreshing token, uploading files from the web application by different application users, and sharing the file for public and take the file id and alternate link id to the web application for thumb preview. With your help I made it.
A little doubt remains. Kindly clarify me if your valuable time permits.



require('http.php');
require('oauth_client.php');
require('database_oauth_client.php');
require('mysqli_oauth_client.php');
//Google sources
require("src/Google_Client.php");
require("src/contrib/Google_Oauth2Service.php");
require('src/contrib/Google_DriveService.php');
include('../config.php'); //database config file
$client = new mysqli_oauth_client_class;

$client->database = array(
'host'=>$dbhost,
'user'=>'root',
'password'=>$dbpasswd,
'name'=>'hf',
'port'=>$dbport,
'socket'=>'/var/lib/mysql/mysql.sock'
);
$client->server = 'Google';
$client->offline = true;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].
dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/test4.php';
$client->client_id = '1011698737016.apps.googleusercontent.com'; $application_line = __LINE__;
$client->client_secret = 'REgkh8csx65DTS7dU67Tcr54';
if(strlen($client->client_id) == 0
|| strlen($client->client_secret) == 0)
die('Please go to Google APIs console page '.
'http://code.google.com/apis/console in the API access tab, '.
'create a new client ID, and in the line '.$application_line.
' set the client_id to Client ID and client_secret with Client Secret. '.
'The callback URL must be '.$client->redirect_uri.' but make sure '.
'the domain is valid and can be resolved by a public DNS.');

/* API permissions
*/
$client->scope = 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile '.
'https://www.googleapis.com/auth/drive';
$client->user = 1;

if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;

}
elseif(strlen($client->access_token))
{


/*passing to google class*/

$apiclient = new Google_Client();
$apiclient->setApplicationName('');
$apiclient->setScopes(array('https://www.googleapis.com/auth/userinfo.email ',
'https://www.googleapis.com/auth/userinfo.profile ',
'https://www.googleapis.com/auth/drive'));
$apiclient->setClientId('');
$apiclient->setClientSecret('');
$apiclient->redirect_uri = '';
$apiclient->setAccessType('offline');
$apiclient->setDeveloperKey('');
$apiclient->setUseObjects(true);
$service= new Google_DriveService($apiclient);

$apiclient->setAccessToken(json_encode($client->refresh_token));




/* $success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo',
'GET', array(), array('FailOnAccessError'=>true), $user); */

/*
* Once you were able to access the user account using the API
* you should associate the current OAuth access token a specific
* user, so you can call the API without the user presence, just
* specifying the user id in your database.
*
* In this example the user id is 1 . Your application should
* determine the right user is to associate.
*/
if($success)
{
$success = $client->SetUser(1);
echo '<form action="test4.php" method="post"';
echo 'enctype="multipart/form-data">';
echo '<label for="file">Filename:</label>';
echo '<input type="file" name="file" id="file"><br>';
echo '<input type="submit" name="submit" value="Submit"> ';
echo '</form>';

if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
//$gclient=$client;
if ($_FILES["file"]["name"]!="")
{
$data = file_get_contents($_FILES["file"]["tmp_name"]);
//$parameters = array();
$parameters = array(
'Authorization:' => "Bearer ".$client->access_token,
);
$file_name = $_FILES["file"]["name"];
$content_type = $_FILES["file"]["type"];
$data = file_get_contents($_FILES["file"]["tmp_name"]);
$parameters = array();
//$parameters=array ("title"=>$file_name,);
$success = $client->CallAPI(
'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
'POST', $parameters, array('FailOnAccessError'=>true,
'RequestContentType'=>$content_type, 'RequestBody'=>$data), $upload);
var_dump($upload);
if($success)
{

$permission = new Google_Permission();
$permission->setValue('');
$permission->setType('anyone');
$permission->setRole('reader');
$service->permissions->insert($upload->id, $permission);

}

}

echo 'Finished service Configuration';
}



}
}
$success = $client->Finalize($success);
}
if($client->exit)
exit;
if($success)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Google OAuth client results</title>
</head>
<body>
<?php
echo '<h1>', HtmlSpecialChars($user->name),
' you have logged in successfully with Google!</h1>';
echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
?>
</body>
</html>
<?php
}
else
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php
}

?>



=====================================================================
$service->permissions->insert($upload->id, $permission);



The above line is giving an error. Is is possible to use both classes at the same time(mysqli_oauth_client_class and Google_Client())



Fatal error: Uncaught exception 'Google_AuthException' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.'

With best regards,

Byju


  8. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2014-05-05 22:25:45 - In reply to message 7 from Byju Chalad
No, don't mix those classes. It doesn't make sense because the OAuth client gets the tokens you need for the other class to work but they do not communicate in any way.

You need to follow the API documentation to see what parameters it takes for the API calls you want to do.

developers.google.com/drive/v2/refe ...

  9. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Byju Chalad Byju Chalad - 2014-05-08 12:59:12 - In reply to message 8 from Manuel Lemos
Dear Manuel Lemos,

Thank you for kind help. Once again i am here at your foot requesting some more clarification.
My module is working fine.
Now it is uploading the file into google drive using an email id exclusively created for this web application.
After upload it set the title of the file using the PUT API call.
Then it shares the uploaded file for public access using a POST Api call.

The final one i am getting errors. The final GET Api call is for getting the thumbnail image of the uploaded file.

The call needs only GET request
GET https://www.googleapis.com/drive/v2/files/{fileid}




/*begin google */
if($mimetype='application/msword')
{
require('http.php');
require('oauth_client.php');
require('database_oauth_client.php');
require('mysqli_oauth_client.php');
$client = new mysqli_oauth_client_class;
$client->database = array(
'host'=>'localhost',
'user'=>'xxxxxxxx',
'password'=>'xxxxxxx',
'name'=>'xxxxxxxx',
'port'=>'3306',
'socket'=>'/var/lib/mysql/mysql.sock'
);
$client->server = 'Google';
$client->offline = true;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = 'http://www.humanistforum.in/gl2/main.php';
$client->client_id = '1011698737016-5m1jhn3m2ab7ag9ae000sireuqdk9aju.apps.googleusercontent.com'; $application_line = __LINE__;
$client->client_secret = 'UgLiysK54PBK4wKKciWe8rYE';
$client->scope = 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile '.
'https://www.googleapis.com/auth/drive';
$client->user = 1;
if(($success = $client->Initialize()))
{
if(($success = $client->Process()))
{
if(strlen($client->authorization_error))
{
$client->error = $client->authorization_error;
$success = false;
}
elseif(strlen($client->access_token))
{
if($success)
{
$success = $client->SetUser(1);
$data = file_get_contents($tmpFile);
$parameters = array(
'Authorization:' => "Bearer ".$client->access_token,);
$file_name = $filename;
$content_type =$mimeType;
$parameters = array();
$success = $client->CallAPI(
'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
'POST', $parameters, array('FailOnAccessError'=>true,
'RequestContentType'=>$content_type, 'RequestBody'=>$data), $upload);

$summary =$upload->alternateLink;
$description=$upload->id;


if($success)
{
$parameters = new stdClass;
$parameters->title = $file_name;
$parameters->editable=true;
$parameters->copyable=true;
$parameters->writersCanShare=ture;
$success = $client->
CallAPI(
'https://www.googleapis.com/drive/v2/files/'.$upload->id, 'PUT',
$parameters,array('FailOnAccessError'=>true,
RequestContentType=>'application/json'), $upload);
$parameters=new stdClass;
$parameters->role="reader";
$parameters->type= "anyone";
$success = $client->
CallAPI(
'https://www.googleapis.com/drive/v2/files/'.$upload->id.'/permissions',
'POST ', $parameters,array('FailOnAccessError'=>true,
'RequestContentType'=>'application/json'), $upload);
/*=============================Here I am facing the problem
var_dump($upload);
$parameters = new stdClass; $success = $client->
CallAPI(
'https://www.googleapis.com/drive/v2/files/'.$description, 'GET',
$parameters,array('FailOnAccessError'=>true,
RequestContentType=>'application/json'), $upload);
$description=$description.$upload->thumbnailLink;
/*=====================================================
var_dump($upload);

}
}
}
$success = $client->Finalize($success);
}
}
}
/*end google*/

  10. Re: Google drive api $parameters usage   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2014-05-14 22:44:28 - In reply to message 9 from Byju Chalad
What errors are you getting?

 
  1 - 10   11 - 12