Google Cloud Storage PHP Client on a server

skeemer • September 10, 2014


This example uses, PHP 5.4+ syntax. I used composer for loading up the client.

require: {
 "google/apiclient": "1.0.*@beta"

Access the Google Developers Console and go to the APIs & Auth > Credentials page. Click Create new Client ID and select Service Account. That will download a key file that we will need to put somewhere accessible by the script. I'm putting it in the same folder for this example, but you don't want it downloadable. Next click Create new Key and select Server Key. The following constants are just straight copies from this page, except the project id, which is found as the Project Number on the Overview page.

define('GAPI_CLIENT_ID', '');
define('GAPI_EMAIL_ADDRESS', '');
define('GAPI_API_KEY', '');
define('GAPI_PROJECT_ID', '');

$google_cert = new Google_Auth_AssertionCredentials(
  file_get_contents(__DIR__ . '/key.p12')

$google_client = new Google_Client();

$gcs = new Google_Service_Storage($google_client);

$list = $gcs->buckets->listBuckets(GAPI_PROJECT_ID);
echo "\n";

The second parameter of Google_Auth_AssertionCredentials constructor is an array of services/APIs that you want to access. All the examples I found listed URLS, but I found that they are usually a constant on each service's class.