i am using google drive file upload code. The following code runs correct in browser. But if i try to do it we error as : fgets() expects parameter 1 to be resource, string given
I have tried many solution but its not working. Please guide me how to use this code for web service to upload file to google drive.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
function uploadFile()
{
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if(!defined("STDIN")) define("STDIN", "fopen('php://stdin','r')");
$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));
//$authCode = trim(file_get_contents(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('Test document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('upload.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
}
Thanks
STDIN is a command line instruction and it isn't a direct valid php statement ..
What i did was :
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$authUrl = $client->createAuthUrl();
print $authurl
$authCode = ''; // insert the verification code that you get after going to url in $authurl
file_put_contents('token.json', $client->authenticate($authCode));
After executing this much you'll get your authentication info in the json file token.json ... And you can use the following to upload ... :
$service = new Google_DriveService($client);
$client->setAccessToken(file_get_contents('token.json'));
//Insert a file
..... // rest the same
Once you get your json don't run the top codes again ... Just use the token.json everytime to upload/download ....
Related
Hi Im trying Google drive integration v3 in php to upload file from my web page i do not want to use picker. I have successfully done oauth and login. I can create a file in the drive but with empty data. the error i get is permission to write i have given public access to that folder. How can i solve this and write the content to that file.
My code after auth(successfull) redirect.
first.php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('conf/client_id.json');
//$scope='https://www.googleapis.com/auth/drive.file';
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope(Google_Service_Drive::DRIVE_FILE);
$client->addScope(Google_Service_Drive::DRIVE);
$client->addScope(Google_Service_Drive::DRIVE_APPDATA);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Drive($client);
$data = file_get_contents("a.png");
// create and upload a new Google Drive file, including the data
$file = new Google_Service_Drive_DriveFile($client);
$file->setName('img_'.uniqid().'.png');
$file->setMimeType('image/png');
//$parent = new Google_ParentReference();
//$parent->setId("0B687nRLFFN08ZXg0WU9Zb3VQaEE");
//$file->setParents(array($parent));
//$file->setParents(array('setId'=>"0B687nRLFFN08ZXg0WU9Zb3VQaEE"));
$createdFile = $service->files->create($file, array(
'data' => file_get_contents("a.png"), //$data
'mimeType' => 'image/png',
'uploadType' => 'media'
));
}
else {
$redirect_uri='http://'.$_SERVER['HTTP_HOST'].'/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I am trying to upload a tar.gz file (300MB) to Google drive but for some reason this is not working.
Have already tried to change the mime-type but with no success.
What I am doing wrong?
This is the code:
<?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('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($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_Service_Drive_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.tar.gz');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
I was trying to submit file to Google Drive. Though the file is uploaded to drive, I am getting error after hitting accept button.
<?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('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://localhost/pdf/quickstart.php');
$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('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
Error messages:
Notice: Use of undefined constant STDIN - assumed 'STDIN' in C:\LocalServer\htdocs\pdf\quickstart.php on line 18
Warning: fgets() expects parameter 1 to be resource, string given in C:\LocalServer\htdocs\pdf\quickstart.php on line 18
How can be fixed
STDIN is a command line instruction and it isn't a direct valid php statement ..
What i did was :
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('**********************');
$client->setClientSecret('*********');
$client->setRedirectUri('*********');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$authUrl = $client->createAuthUrl();
print $authurl
$authCode = ''; // insert the verification code that you get after going to url in $authurl
file_put_contents('token.json', $client->authenticate($authCode));
After executing this much you'll get your authentication info in the json file token.json ... And you can use the following to upload ... :
$service = new Google_DriveService($client);
$client->setAccessToken(file_get_contents('token.json'));
//Insert a file
..... // rest the same
Once you get your json don't run the top codes again ... Just use the token.json everytime to upload/download ....
I am trying to learn a simple web app (PHP) using Google drive API.
Display list of files in the drive.
Add a new file to the drive.
Code as follows:
<?php
session_start();
$url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $url_array[0];
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();
$client->setClientId(''); // Kept my id
$client->setClientSecret(''); //kept my key
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code'])) {
$_SESSION['accessToken'] = $client->authenticate($_GET['code']);
header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
$client->authenticate();
}
It works fine till here. The app gets authenticated and redirects back to my app.
Now, I try displaying list of files.
Problem code:
$service = new Google_DriveService($client);
$result = array();
$files = $service->files->listFiles();
$result = array_merge($result, $files->getItems());
print_r($result);
I get this error:
Error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/drive/v2/files: (401) Login Required' in C:\wamp\www\Sample\google-api-php-client\src\io\Google_REST.php
Can someone please help in correcting me and also I would be thankful in sharing simple code how to insert a doc.
Add this line after $client->authenticate();:
$client->setAccessToken($accessToken);
how to upload a file through the html form either by file upload or Google file picker and storing the fil url to mysql database ?
i tried to upload file through file upload and passing it to the $file variable in the below code, the file is uploading but is invalid in the Google drive ?
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$myfile=$_REQUEST['file'];
$type=mime_content_type($myfile);
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('');
$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('My New document');
$file->setDescription('A test document');
$file->setMimeType($type);
$data = file_get_contents($myfile);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $type,
));
print_r($createdFile);
?>
use $myfile=$_FILES['file']['tmp_name']; instead of $myfile=$_REQUEST['file'];
You use 'trim(fgets(STDIN));' this won't work from a html page.
Your app have to read your authcode from $_GET['code'] when google redirect the authorized user back to your site.
You can test this with the code shown below. To test it you have to save the code as index.php and make it available on http://localhost/.
setRedirectUri only allow to redirect to a main domain (http://localhost/test.php is not allowed).
When $_GET['code'] is empty you will be redirected to accounts.google.com.
After you grant the app you will be send back to http://localhost/?code={your authcode}.
Now you can save the authcode to use it on other pages too.
In this test code the file upload form will submit to http://localhost/?code={your authcode} cause the action attribute is empty.
print_r($createdFile); will give you the information to store the file url in your database.
Don't forget setup up an Google API console project to get your credentials first, see also http://enarion.net/programming/php/google-client-api/google-client-api-php/
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
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 APIs Console
$client->setClientId('**********.apps.googleusercontent.com');
$client->setClientSecret('********************');
$client->setRedirectUri('http://localhost/');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if(empty($_GET['code']))
{
$client->authenticate();
}
?>
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="file">
<input type="submit" value="verzenden">
</form>
<?
if(!empty($_FILES['file']['tmp_name']))
{
$myfile=$_FILES['file']['tmp_name'];
$type=mime_content_type($myfile);
$service = new Google_DriveService($client);
// Exchange authorization code for access token
$accessToken = $client->authenticate($_GET['code']);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My New document');
$file->setDescription('A test document');
$file->setMimeType($type);
$data = file_get_contents($myfile);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $type,
));
print_r($createdFile);
}