Skip to content

Instantly share code, notes, and snippets.

@theacodes
Created January 19, 2015 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theacodes/c7c1a4ced0e07417e067 to your computer and use it in GitHub Desktop.
Save theacodes/c7c1a4ced0e07417e067 to your computer and use it in GitHub Desktop.
Compute Engine PHP OAuth Example
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token');
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Metadata-Flavor: Google']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);
// The client library expects the 'created' property to be set on the access token.
$token = json_decode($resp, true);
$token['created'] = time();
$token = json_encode($token, true);
$client = new \Google_Client();
$client->setAccessToken($token);
$service = new \Google_Service_Storage($client);
$gso = new \Google_Service_Storage_StorageObject();
$resp = $service->objects->listObjects('even-arc-775-gce-deployment');
@Robarelli
Copy link

For reference (uploading):

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://metadata/computeMetadata/v1/instance/service-accounts/default/token');
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Metadata-Flavor: Google']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$resp = curl_exec($curl);
curl_close($curl);

// The client library expects the 'created' property to be set on the access token.
$token = json_decode($resp, true);
$token['created'] = time();
$token = json_encode($token, true);

$client = new \Google_Client();
$client->setAccessToken($token);
$service = new \Google_Service_Storage($client);
$gso = new \Google_Service_Storage_StorageObject();
$gso->setName($dest_path.$filename);
$params = [
    'data'          => file_get_contents($src_path.$filename),
    'mimeType'      => 'application/octet-stream',
    'uploadType'    => 'media'
];
$resp = $service->objects->insert('bucket-name', $gso, $params);

@Robarelli
Copy link

Using the updates in 623bfe9

$client = new \Google_Client();
$oauth = new \Google_Auth_ComputeEngine($client);
$client->setAccessToken($oauth->acquireAccessToken());

$service = new \Google_Service_Storage($client);
$gso = new \Google_Service_Storage_StorageObject();
$gso->setName($destPath.$filename);
$params = [
    'data'          => file_get_contents($srcPath.$filename),
    'mimeType'      => 'application/octet-stream',
    'uploadType'    => 'media'
];

return $service->objects->insert('bucket-name', $gso, $params);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment