For whatever reason you can’t use gsutil, gcloud, or a client library, you could request an access token directly. This example uses PHP 5.2 (the PHP client library only works with PHP 5.3+). Please make sure your instance has access to the correct scopes and that a service account is enabled.
public function setGoogleStorage() { // Get access code $access_token_request_url = "http://metadata/computeMetadata/v1/instance/service-accounts/default/token"; $google_ch = curl_init(); curl_setopt($google_ch, CURLOPT_URL, $access_token_request_url); curl_setopt($google_ch, CURLOPT_HTTPHEADER, array('Metadata-Flavor: Google')); curl_setopt($google_ch, CURLOPT_RETURNTRANSFER, true); $c_result = curl_exec($google_ch); list($at, $exp, $toktype) = explode(",", $c_result); list($a, $access_token) = explode(":", $at); curl_close($google_ch); $google_header = array("Authorization: Bearer $access_token"); $this->setRequestHeader($google_header); }
// READ $storage_url = "https://storage.googleapis.com/my-test-bucket/my-test-file.txt"; $read_request = new RestRequest($storage_url, "GET", ""); $read_request->setGoogleStorage(); $read_request->execute(); $resp_str = $read_request->getResponseBody(); // CREATE $storage_path = "https://storage.googleapis.com/my-test-bucket/my-test-upload-file.txt"; $file_contents = file_get_contents("/tmp/my-test-upload-file.txt"); $write_request = new RestRequest($storage_path, "PUT", $file_contents); $write_request->setGoogleStorage(); $write_request->execute(); $write_response = $write_request->getResponseInfo();
Related Resources:
- https://cloud.google.com/compute/docs/metadata?hl=en
- https://cloud.google.com/compute/docs/authentication
Recent Comments