I am trying to download a Google Spreadsheet file but I am getting an error every time. I was basically doing what it is written here: how to write a google drive download file to a directory using php , But I am getting: Warning: Undefined property: Google_Service_Sheets::$files in when I run the following code:
$client = new \Google_Client();
$client->setApplicationName('GoogleSheets');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('credentials.json');
$service = new Google_Service_Sheets($client);
$fileId = mySpreadSheetID;
// Retrieve filename.
$file = $service->files->get($fileId);
$fileName = 'Test_'.time();
// Download a file.
$content = $service->files->get($fileId, array("alt" => "media"));
$handle = fopen("./".$fileName, "w+");
while (!$content->getBody()->eof()) {
fwrite($handle, $content->getBody()->read(1024));
}
fclose($handle);
What am I doing wrong?
You can only do it that way if its a binary type file for a Google sheet you will need to export it. Also you should be creating a drive service and not a sheets service.
$service = new Google_Service_Drive($client);
$response = $service->files->export($createdFile->id, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', array('alt' => 'media' ));
$content = $response->getBody()->getContents();
file_put_contents('test.xlsx',$content);
Related
I am working on a project in which I need to upload a .xlsx file to my google drive via Google Drive API. Then also to get back the link so I can store it into MySQL Database.
The Uploading part is done. The problem is, how can I get back the file link so I can edit it using Google Sheets. I think I need to add Custom File ID To my file. I really don't know where to add it. My code is below:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$filefullname=$_GET['accid'].' '.$_GET['name'].'.xlsx';
// UPLOADING OF FILE TO GOOGLE DRIVE////////////////////////////////////
//fopen('./client_sheets/'.$_GET['name'], "w");
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_Service_Drive_DriveFile();
$file_path = './client_sheets/'.$filefullname;
$mime_type = finfo_file($finfo, $file_path);
$file->setName($filefullname);
$file->setDescription('This file contains details about: '.$filefullname.' || Client of GT Security');
$file->setMimeType($mime_type);
$file->setName($filefullname);
$createdFile = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type,
'fields' => 'id'
)
);
print 'File ID: %s' % $createdFile->getId();
More info: I used PhpSpreadsheet to create the .xlsx file. Please can somebody add the FileID Field for me? Also, can somebody explain to me how to get the file link so I can edit it using Google Sheets?
In this case you can use the Google Drive automatic conversion feature. When you create the file in google drive it will be automatically converted to a spreadsheet file. So that you can open it via the spreadsheet service and get the url you need to store in your db.
Create and convert the .xlsx to a spreadsheet file:
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $filefullname,
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents($file_path);
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
Get the spreadsheet url:
$spreadsheetId = $file->id;
$sheetService = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
$sheetUrl = $response->getSpreadsheetUrl();
References:
PHP Spreadsheet class methods
Import to Google Docs types
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
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'm totally new to Google Cloud Storage (since I used Amazon S3 until now).
I want to set up my web application, so that users can download files directly from the Google Cloud Storage.
I've already tried it, using the Google Api PHP Client, but didn't get a functionally code.
I've uploaded a test file named "test.jpg" to my bucket "test-bucket-46856" which I want to download via signed url (so that users only have time limited access), but I have no idea how to get this started.
Please help. Thanks.
//Edit:
Found the perfect solution. Here the link for all others who are also searching for this solution:
https://gist.github.com/stetic/c97c94a10f9c6b591883
<?php
/*
* PHP Example for Google Storage Up- and Download
* with Google APIs Client Library for PHP:
* https://github.com/google/google-api-php-client
*/
include( "Google/Client.php" );
include( "Google/Service/Storage.php" );
$serviceAccount = "1234-xyz#developer.gserviceaccount.com";
$key_file = "/path/to/keyfile.p12";
$bucket = "my_bucket";
$file_name = "test.txt";
$file_content = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/devstorage.read_write'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$storageService = new Google_Service_Storage( $client );
/***
* Write file to Google Storage
*/
try
{
$postbody = array(
'name' => $file_name,
'data' => $file_content,
'uploadType' => "media"
);
$gsso = new Google_Service_Storage_StorageObject();
$gsso->setName( $file_name );
$result = $storageService->objects->insert( $bucket, $gsso, $postbody );
print_r($result);
}
catch (Exception $e)
{
print $e->getMessage();
}
/***
* Read file from Google Storage
*/
try
{
$object = $storageService->objects->get( $bucket, $file_name );
$request = new Google_Http_Request($object['mediaLink'], 'GET');
$signed_request = $client->getAuth()->sign($request);
$http_request = $client->getIo()->makeRequest($signed_request);
echo $http_request->getResponseBody();
}
catch (Exception $e)
{
print $e->getMessage();
}
I've written a short php script in order to upload a local file to my Google cloud storage bucket, using PHP client library (https://github.com/google/google-api-php-client).
I can authenticate, I can list the remote content, but simply I can't upload anything, since I obtain an error 400 ("Uploads must be sent to the upload URL").
This is my full script, that I modified following from some tutorial found online:
<?php
require_once "/var/www/local/google-api-php-client-master/src/Google/autoload.php"; // API Google library
define('GAPI_CLIENT_ID', 'XXX.apps.googleusercontent.com');
define('GAPI_EMAIL_ADDRESS', 'YYY#developer.gserviceaccount.com');
define('GAPI_API_KEY', 'xxxmyapikeyxxx');
define('GAPI_PROJECT_ID', 'projectid');
// certificate file
define('KEY_FILE_LOCATION', '/var/www/local/passphrase.p12');
// bucket name
$bucket = "mybucketname"
// remote file name
$file_name = "test.mp3";
// file to upload
$local_file = "/var/www/local/test.mp3";
$google_cert = new Google_Auth_AssertionCredentials(
GAPI_EMAIL_ADDRESS,
array('https://www.googleapis.com/auth/devstorage.full_control'),
file_get_contents(KEY_FILE_LOCATION)
);
$google_client = new Google_Client();
$google_client->setAssertionCredentials($google_cert);
$google_client->setDeveloperKey(GAPI_API_KEY);
$service = new Google_Service_Storage($google_client);
$obj = new Google_Service_Storage_StorageObject();
$obj->setName($file_name);
$obj->setContentType('media');
$obj->setSize(filesize($local_file));
$dataFILE['data']=file_get_contents($local_file);
$dataFILE['uploadType']="media";
$service->objects->insert(
$bucket,
$obj,
$dataFILE
);
?>
What's wrong with it??