I am trying to upload a pdf to google drive as a service account in php.
I get a browser error: ERR_CONNECTION_RESET when trying to upload.
I got the code from here:
https://developers.google.com/drive/web/service-accounts#next_steps
and
https://developers.google.com/drive/v2/reference/files/insert
<?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";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxx#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'API Project-xxx.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* #return Google_DriveService service object.
*/
function buildService() {
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$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);
}
/**
* Insert new file.
*
* #param Google_DriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service=buildService();
$title='test';
$description='qqq';
$parentId='';
$mimeType='application/pdf';
$filename='doc.pdf';
insertFile($service, $title, $description, $parentId, $mimeType, $filename)
?>
Related
I have followed https://developers.google.com/drive/api/v2/reference/files/list, successful! I got it all. But not my 'drive'. I received a warning 'You need to be granted access here. So what should I do to fix the above error?
I created a new project, Service account keys and OAuth 2.0 client IDs. but it's bad it doesn't properly link to my 'google drive' account
This is my whole code
<?php
session_start ();
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';
require_once 'vendor/autoload.php';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxx#phim-240702.iam.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'phim-240702-a98343eb742a.p12';
function buildService(){
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$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->setApplicationName("googletest5");
$client->setDeveloperKey("b2016fa55e916faf35337ccb1db830ecdb590cc3");
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
/**
* Insert new file.
*
* #param Google_Service_Drive $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_Service_Drive_DriveFile The file that was inserted. NULL is
* returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => '$mimeType',
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
/**
* Retrieve a list of File resources.
*
* #param Google_Service_Drive $service Drive API service instance.
* #return Array List of Google_Service_Drive_DriveFile resources.
*/
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array(
'maxResults' => '100'
);
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
try {
$root_id = null;
$service = buildService();
print_r(retrieveAllFiles($service));
}catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
?>
What you need to remember is that a Service account is not you. A service account is a dummy user. It has its own google drive account. when you upload the files to the service accounts drive account they are only accessible by that account as it is the owner of it.
Share a drive
If you want it to be able to access files on your personal drive account you will need to grant it access to them by sharing them with the service accounts email address. This is how service accounts are pre approved.
getting path
As for getting the path of a file there is no easy way to do that you will need to step your way though it by getting the file, then getting its parent, followed by getting any more parents until you hit the top and build it up that way.
I know how do upload an object to Aws S3 Bucket like this:
try {
$oClientAws->putObject(array(
'Bucket' => 'bucket_test',
'Key' => 'fileName.jpg',
'Body' => fopen('path/to/file/fileName.jpg', 'r'),
'ACL' => 'public-read',
));
}
catch (Aws\Exception\S3Exception $e) {}
But i don't know how to download an object i can use $oClientAws->getObject(parms...) and change the content type of the header but this just show my file on the browser, but don't download the file.
tks!
File can be downloaded from s3 bucket using getObject method of s3client API
/**
* Gets file stored in Amazon s3 bucket.
*
* #param string $awsAccesskey , access key used to access the Amazon bucket.
* #param string $awsSecretKey , secret access key used to access the Amazon bucket.
* #param string $bucketName , bucket name from which the file is to be accessed.
* #param string $file_to_fetch , name of the file to be fetched, if the file is with in a folder it should also include the folder name.
* #param string $path_to_save , path where the file received should be saved.
* #return boolean true if the file is successfully received and saved else returns false.
*/
function get_from_s3_bucket( $awsAccesskey, $awsSecretKey, $bucketName, $file_to_fetch, $path_to_save ) {
try {
$bucket = $bucketName;
require_once('S3.php');
$s3 = new S3( $awsAccesskey, $awsSecretKey );
$object = $s3->getObject( $bucket, $file_to_fetch, $path_to_save );
if ( $object->code == 200 ) {
return true;
} else {
return false;
}
} catch ( Exception $e ) {
return false;
}
}
Refer the below link for more guidance:
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html
Using the S3 standalone class (which I have found isn't much different from the AWS SDK) getObject has a saveTo param where you pass a filename to save the file to... Check out the method:
/**
* Get an object
*
* #param string $bucket Bucket name
* #param string $uri Object URI
* #param mixed $saveTo Filename or resource to write to
* #return mixed
*/
public static function getObject($bucket, $uri, $saveTo = false)
{
$rest = new S3Request('GET', $bucket, $uri, self::$endpoint);
if ($saveTo !== false)
{
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = #fopen($saveTo, 'wb')) !== false)
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
Here's a link to obtain the class: https://aws.amazon.com/code/1448
Hope this helps.
I am creating a txt/html file in google drive as document using the google drive sdk. the code creates successfully the document.
My question is that it is possible that it can also set the file permission as read-only file?
this is my code in creating the document,
$mkFile = $this->_service->files->insert($file, array('data' => $subcontent, 'mimeType' => 'text/html', 'convert' => true));
You can create Permission to Anyone only reader.
Code based from documentation Google Drive API V3:
https://developers.google.com/drive/api/v3/reference/permissions/create
public function permissionAnyone($fileId) {
$permissions = new Google_Service_Drive_Permission(array(
'role' => 'reader',
'type' => 'anyone',
));
try {
$result = $this->service_drive->permissions->create($fileId, $permissions);
} catch (Exception $e) {
$result = $e->getMessage();
}
return $result;
}
you can use permissions.patch to update the permissions for a file after it has been inserted. There is currently a bug in the API that doesn't allow you to set the permissions at the time you insert the file. You have to patch them after the file has been placed on drive.
Code ripped from documentation link above.
/**
* Patch a permission's role.
*
* #param Google_Service_Drive $service Drive API service instance.
* #param String $fileId ID of the file to update permission for.
* #param String $permissionId ID of the permission to patch.
* #param String $newRole The value "owner", "writer" or "reader".
* #return Google_Servie_Drive_Permission The patched permission. NULL is
* returned if an API error occurred.
*/
function patchPermission($service, $fileId, $permissionId, $newRole) {
$patchedPermission = new Google_Service_Drive_Permission();
$patchedPermission->setRole($newRole);
try {
return $service->permissions->patch($fileId, $permissionId, $patchedPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
To upload files to Google Drive using service account, I have written the following code which is from this link: https://developers.google.com/drive/web/service-accounts
My code:
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 = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* #return Google_DriveService service object.
*/
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);
}
function uploadFile($service, $mime, $src) {
//Insert a file
$file = new Google_DriveFile();
$file->setMimeType($mime);
$data = file_get_contents($src);
try {
//ERROR HERE: cannot insert (upload) file
$createdFile = $service->files->insert($file,
array(
'data' => $data,
'mimeType' => $mime,
'convert' => true,
)
);
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service = buildService();
When I call the buildService() method, it gives me an error:
Catchable fatal error: Object of class Google_AssertionCredentials could not be converted to string in /opt/lampp/htdocs/ajaxGoogleDrive/google-api-php-client/src/auth/Google_OAuth2.php on line 197
Where am I going wrong?
I need to create spreadsheet using google drive PHP API, how can i do that ?
i already have code put it always get untitled file and when i click on it there is no data here is my code:
/**
* Insert new file.
*
* #param apiDriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $data) {
$file = new DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
try {
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
print_r($createdFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
if(isset($_POST['insertFile'])){
$service = new apiDriveService($client);
insertFile($service,'Google Maps Mrakers.txt','ADD Google Map Mrakers To File',NULL,'text/plain',$_POST['data']);
exit;
}
You are having this issue because you are using an out-of-date version of the PHP client library. Please sync your client to the trunk of the project repository.
You would have to re-write some of your code as the client library has been refactored since you first wrote your code. The reference guides in the Google Drive SDK documentation have been updated to reflect this refactoring.
To create a Google Spreadsheet, insert a file without content with its mimeType set to application/vnd.google-apps.spreadsheet.