Kristijan
Kristijan

Reputation: 5885

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?

Upvotes: 3

Views: 2198

Answers (2)

Bernardo Bicalho
Bernardo Bicalho

Reputation: 96

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

Upvotes: 4

Christiaan
Christiaan

Reputation: 2725

You can use the JSON api.

To see it in action go here:

https://developers.google.com/apis-explorer/#p/storage/v1/storage.objects.list

Then enable OAuth2 in the top right and fill in your bucket name to see an example request and response.

Upvotes: -1

Related Questions