Downloading files from Google Cloud Storage using the PHP API

skeemer • September 11, 2014


Downloading files was something else I was barely able to piece together. I found an outdated version, but the SDK had changed enough that it wasn't operable.

$gcs = new Google_Service_Storage($google_client);
$filename = 'test_file.txt';

try {
  // Retrieve object
  $object = $gcs->objects->get(GAPI_BUCKET_NAME, $filename);
  $data = $google_client->getAuth()->authenticatedRequest(new Google_Http_Request($object->getMediaLink()));
  file_put_contents($filename, $data->getResponseBody());
} catch (Google_Service_Exception $e) {

If you're doing this in a class or method and just want to pass $gcs, then you can get the client with using $gcs->getClient().

$data = $gcs->getClient()->getAuth()->authenticatedRequest(new Google_Http_Request($object->getMediaLink()));