Google Cloud Storage File Download via PHP - php

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

Related

Download Google SpreadSheet Google API PHP

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

Microsoft OneDrive SDK run as cron

Hi am using this OneDrive SDK . https://github.com/krizalys/onedrive-php-sdk . I am using PHP. What I need is to create a cronjob that will fetch my files in OneDrive and save it to my local directory. It works fine following the tutorial in the SDK. However, the way that SDK works is it needs you to be redirected to Microsoft account login page to be authenticated.
This will require a browser. My question, is it possible to do this by just running it in the backend like a cron? I can't seem to find a way to do it using the SDK. In Google, they will provide you a key to access the services without logging in every time. I am not sure about OneDrive.
$localPath = __DIR__.'/uploads/';
$today = date('Y-m-d');
$folder = $client->getMyDrive()->getDriveItemByPath('/'.$today);
echo "<pre>";
try {
$files = $folder->getChildren();
$createdDirectory = $localPath.$today;
// Check if directory exist
if(is_dir($createdDirectory)){
echo "\n"." Directory ".$createdDirectory." already exists, creating a new one..";
// Create new directory
$uuid1 = Uuid::uuid1();
$createdDirectory = $createdDirectory.$uuid1->toString();
echo "\n".$createdDirectory." created..";
}
// Create directory
mkdir($createdDirectory);
echo "\n".count($files)." found for ".$today;
// Loop thru files inside the folder
foreach ($files as $file){
$save = $file->download();
// Write file to directory
$fp = fopen($createdDirectory.'/'.$file->name, 'w');
fwrite($fp, $save);
echo("\n File ".$file->name." saved!");
}
} catch (Exception $e){
die("\n".$e->getMessage());
}
die("\n Process Complete!");
My code is something like that in the redirect.php
It doesn't look like that SDK supports the Client Credentials OAuth Grant. Without that, the answer is no. You may want to look at the official Microsoft Graph SDK for PHP which supports this via the Guzzle HTTP client:
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;

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

How to upload exist XLS file in Google Spread Sheet, php?

I use
"google/apiclient": "1.1.7",
"asimlqt/php-google-spreadsheet-client": "2.3.7",
"phpoffice/phpexcel": "1.8.1"
And I create new spread sheet in google drive
"google/apiclient":
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$insertArray = [
'mimeType' => 'application/vnd.google-apps.spreadsheet',
];
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$e->getMessage()
}
and I have alternativeUrl - https://docs.google.com/spreadsheets/d/xxxxx/edit?usp=drivesdk and this is ok, go to this url I have emty google spread sheet
And I know how to upload exist xls file, generate in PHPExel and save and upload in google drive
"phpoffice/phpexcel":
$phpExcel = new \PHPExcel();
$ews = $phpExcel->getSheet(0);
$ews->setTitle(Reports::LIST_AOG);
$objWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
$path = 'uploads/';
$rootDir = $this->get('kernel')->getRootDir() . '/../web/';
$filePath = $rootDir . $path.$nameFile;
$objWriter->save($filePath);
$fileUpload = new File($filePath);
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload)
];
"google/apiclient":
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($nameFile);
$file->setMimeType($fileUpload->getMimeType());
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$e->getMessage()
}
and I have alternativeUrl - https://drive.google.com/file/d/xxxxxx/view?usp=drivesdk and this is ok, go to this url I see file and button open in GoogleSpreadSheet
and this moment my xls file not googleSpreadSheet, only when I open my file in googleSpreadSheet this file will get googleSpreadSheetId
and I can get google spread sheet by id or title
"asimlqt/php-google-spreadsheet-client":
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$scopeSpreadSheet = $spreadsheetService->getSpreadsheets();
$spreadsheetByTitle = $scope->getByTitle($createdFile->getTitle());
$spreadsheetById = $spreadsheetService->getSpreadsheetById($spreadsheetId);
I try replace momeType file in application/vnd.google-apps.spreadsheet but have in googledrive emty googleSpreadSheet
And I refuse to believe that I can not download my file in googleSpreadSheet immediately or right one request. I try find solution but the two day search yielded no results.
How to download my xls file in googleSpreadSheed in one moment ??? Help please
I find :)
convert boolean Whether to convert this file to the corresponding Google Docs format. (Default: false)
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload),
'convert' => true
];

AWS Multipart upload SDK not working

I need Help on AWS multi-part Upload using PHP 5.3
I am using
1. WAMP Server.
2. PHP 5.3
3. OS: Windows 8
I am trying to upload a Big file to My Amazon S3 bucket.
And tried in many ways. I followed the code procedure from
http://docs.aws.amazon.com/AmazonS3/latest/dev/LLuploadFilePHP.html
I wrote PHP code but I don't know what mistake I did.
My Code:
<?php
require_once './sdk/sdk.class.php';
use \AmazonS3;
$ufile = $_FILES['ufile'];
$filepath = $ufile['tmp_name'];
$bucket = '**My_bkt**';
var_dump($ufile);
print $keyname = \date("Y") . "/" . \date("F") . "/" . \date("d") . "/" . $ufile['name'] . "<BR />";
$api_key = "***my_api_key***";
$secret_key = "***my_secret_key***";
// Define a megabyte.
define('MB', 1048576);
// Instantiate the class
//$s3 = new AmazonS3();
$s3 = new AmazonS3(array(
'key' => $api_key,
'secret' => $secret_key,
));
// 1. Initiate a new multipart upload.
/* #var $response type */
$response = $s3->initiate_multipart_upload($bucket, $keyname);
// Get the Upload ID.
$upload_id = (string) $response->body->UploadId;
// 2. Upload parts.
// Get part list for a given input file and given part size.
// Returns an associative array.
$parts = $s3->get_multipart_counts(filesize($filepath), 3 * MB);
foreach ($parts as $i => $part) {
// Upload part and save response in an array.
$responses[] = $s3->upload_part($bucket, $keyname, $upload_id, array(
'fileUpload' => $filepath,
'partNumber' => ($i + 1),
'seekTo' => (integer) $part['seekTo'],
'length' => (integer) $part['length'],
)
);
}
// 3. Complete multipart upload. We need all part numbers and ETag values.
$parts = $s3->list_parts($bucket, $keyname, $upload_id);
$response = $s3->complete_multipart_upload($bucket, $keyname, $upload_id, $parts);
var_dump($response);
Please help me.
I know you're using the older SDK 1 here, so my answer doesn't apply directly to what you've posted. That said, SDK 1.x is no longer being updated and SDK 2.x is what all new work should be using (as per the AWS SDK for PHP team).
If you do update your project to use SDK 2, then take a look at S3Client::upload(). It should greatly simplify what you're trying to do here.
I have Updated My SDK and Changed My Code like bellow,
////////////////// AWS Code Begin ////////////////////
/////////////////////////// Step 1 /////////////////////////////
$ufile = $_FILES['Filedata'];
$filename = $ufile['tmp_name'];
$filesize = $ufile['size'];
/* * ************ Calculating Number of Parts ******************* */
$number_of_parts = 0;
$r = $filesize % PART; // Remainder
$q = floor($filesize / PART); // Quotient
if ($r != 0) {
$number_of_parts = $q + 1;
} else {
$number_of_parts = $q;
}
$bucket = 'isource123';
$keyname = date("Y") . "/" . date("F") . "/" . date("d") . "/" . $ufile['name'];
///////////////////////////// Step 2 /////////////////////////////
// Create a service builder using a configuration file
$aws = Aws::factory('./aws/Aws/Common/Resources/aws-config.php');
// Get the client from the builder by namespace
$client = $aws->get('S3');
$uploader = \Aws\S3\Model\MultipartUpload\UploadBuilder::newInstance()
->setClient($client)
->setSource($filename)
->setBucket($bucket)
->setKey($keyname)
->setOption('Metadata', array('Foo' => 'Bar'))
->setOption('CacheControl', 'max-age=3600')
->setConcurrency($number_of_parts)
->build();
try {
$uploader->upload();
echo "Upload complete.\n";
} catch (MultipartUploadException $e) {
$uploader->abort();
echo "Upload failed.\n";
}
I updated My SDK to version 2 and it's working fine.

Categories