how can i put file to a certain google drive account? - php

I'm using PHP to put some runtime created files on a specific Google Drive account.
If I'm logged on google with an account and I launch my script, these files will be uploaded on this account, even I use client ID and secret of a different account
Use case:
I'm logged with a#gmail.com, I use my script and files are sent to a#gmail.com's Google Drive instead of b#gmail.com's Google Drive
How can I upload these files to b#gmail.com account even if I'm logged with a#gmail.com account?
Thanks
The ex. code
<?php
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(/*client id*/);
$drive->setClientSecret(/*client secret*/);
$drive->setRedirectUri(/*redirect uri (the same URI in the API configuration)*/);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $service->files->insert($file, array(
'data' => 'example',
'mimeType' => 'text/plain',
));
return true;
EDIT:
I use pathfinder solution and create a service account.
It seems working but I've still a problem: at the end of execution I can't find my file on gDrive...maybe I've done an invomplete configuration, even if I read the doc...
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';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<email_in_api_access>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'google-api-phpclient/<api_key_file>-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$gdrive = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $gdrive->files->insert($file, array(
'data' => 'A test document',
'mimeType' => 'text/plain',
));
return true;

Related

How to see files uploaded to google drive via PHP?

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

google drive integration v3 in php

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));
}

PHP / Google Drive API - Upload tar.gz

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);
?>

Google drive API with service account is not working

I am trying to implement google drive api with my service account .
Warning: file_get_contents() [function.file-get-contents]:
Filename cannot be empty in /home/logic5nv/public_html/projects/
google_drive /gservice.php on line 18
Fatal error: Uncaught exception 'Google_AuthException' with message
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL =
'842613324525-6veubhkhrurplpshiuagmdvk1rtm1q1g#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '8447ce76bbb4956f9cbecd6779371ad3ab8f8e7e-
privatekey.p12';
function buildService() {
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
$service = buildService();
$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);
Try :
function buildService() {
global $SERVICE_ACCOUNT_PKCS12_FILE_PATH,$SERVICE_ACCOUNT_EMAIL,$DRIVE_SCOPE ;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}

upload file to Google drive through html form and store url in input-text box to write to mysql?

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);
}

Categories