Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Google Cloud Storage

I'm trying to use Google Cloud Storage in my PHP project - but not on the AppEngine platform. All the links and tutorials I found always use the AppEngine platform and therefor can use the gs:// links. Does anyone know how to connect and for example list objects in a bucket - or at least connect to the storage trough php without AppEngine?

like image 208
Kristijan Avatar asked Nov 22 '25 10:11

Kristijan


1 Answers

try this code:

set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once("Google/Service/Storage.php");

$client_id = '<client-id>'; //Client ID
$service_account_name = '<service_account_name(email)>'; //Email Address 
$key_file_location = 'key.p12'; //your key.p12 file

echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
    || !strlen($service_account_name)
    || !strlen($key_file_location)) {
  echo missingServiceAccountDetailsWarning();
}

$client = new Google_Client();
$client->setApplicationName("<your application name>");
$service = new Google_Service_Storage($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/devstorage.full_control'),
    $key
);

$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket('<your bucket name>');
$acl->setObject('your object name');

$service = new Google_Service_Storage($client);
$return_value = $service->objects->get('<bucket_name>','<object-name>');
like image 160
Bernardo Bicalho Avatar answered Nov 24 '25 22:11

Bernardo Bicalho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!