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));
}
Related
I have been trying to upload files to my google drive account via service-account using php. I guess the file is successfully uploaded as I can print the file id, file created time and all other information.
Here is my issue: When I login into my google drive account, I cannot see any uploaded file. Where is the file hiding or what should I do?
Here is the code:
require __DIR__ . '/vendor/autoload.php'; //api
$serviceAccount = "xxx#xxxxxx.iam.gserviceaccount.com";
$key_file = "mykey-goes-here.p12";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/drive.file'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("my file name");
$file->setDescription('testing desc');
$file->setMimeType('text/plain');
// Provide file name here and path in below
$result = $service->files->insert($file, array(
'data' => file_get_contents("test.txt"),
//'mimeType' => 'text/plain',
'mimeType' => 'application/octet-stream',
'uploadType' => 'media',
//'uploadType' => 'multipart'
));
// Uncomment the following line to print the File ID
printf("File ID: %s\n", $result->id);
echo "<br><br>";
echo '<pre>'; print_r($result); echo'</pre>';
solution:
I discovered that Files uploaded by service account is not available via UI.
To solve the issue, one need to delegate/authorize the application to use the said service account.
link
I am trying to upload files to google drive using below code
require_once 'google-api-php-client-master/src/google/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/drive');
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
/*$drive_service = new Google_Service_Drive($client);
$files_list = $drive_service->files->listFiles(array())->getItems();
echo json_encode($files_list);*/
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("test");
$file->setMimeType('application/vnd.google-apps.folder');
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
'uploadType' => 'multipart'
));
echo "===".$fileId = $createdFile->id;
}
else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/google/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
and it is giving me insufficient permissions error.
Am i missing something?
I tried using Service account and it worked fine, Is Service account required to upload files using Google Drive API?
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 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 ....
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);
}