Google Cloud Client Library

v0.125.0 2020-02-11 23:07 UTC

This package is auto-updated.

Last update: 2020-02-19 23:02:27 UTC


Idiomatic PHP client for Google Cloud Platform services.

CI Status

PHP Version Status
PHP 7.2 Kokoro CI

Latest Stable Version Packagist Travis Build Status codecov

This client supports the following Google Cloud Platform services at a General Availability quality level:

This client supports the following Google Cloud Platform services at a Beta quality level:

This client supports the following Google Cloud Platform services at an Alpha quality level:

If you need support for other Google APIs, please check out the Google APIs Client Library for PHP.

Quick Start

We recommend installing individual component packages when possible. A list of available packages can be found on Packagist.

For example:

$ composer require google/cloud-bigquery
$ composer require google/cloud-datastore

We also provide the google/cloud package, which includes all Google Cloud clients.

$ composer require google/cloud


Authentication is handled by the client library automatically. You just need to provide the authentication details when creating a client. Generally, authentication is accomplished using a Service Account. For more information on obtaining Service Account credentials, see our Authentication Guide.

Once you've obtained your credentials file, it may be used to create an authenticated client.

require 'vendor/autoload.php';

use Google\Cloud\Core\ServiceBuilder;

// Authenticate using a keyfile path
$cloud = new ServiceBuilder([
    'keyFilePath' => 'path/to/keyfile.json'

// Authenticate using keyfile data
$cloud = new ServiceBuilder([
    'keyFile' => json_decode(file_get_contents('/path/to/keyfile.json'), true)

If you do not wish to embed your authentication information in your application code, you may also make use of Application Default Credentials.

require 'vendor/autoload.php';

use Google\Cloud\Core\ServiceBuilder;


$cloud = new ServiceBuilder();

The GOOGLE_APPLICATION_CREDENTIALS environment variable may be set in your server configuration.

gRPC and Protobuf

Many clients in Google Cloud PHP offer support for gRPC, either as an option or a requirement. gRPC is a high-performance RPC framework created by Google. To use gRPC in PHP, you must install the gRPC PHP extension on your server. While not required, it is also recommended that you install the protobuf extension whenever using gRPC in production.

$ pecl install grpc
$ pecl install protobuf

Cloud Firestore (GA)


require 'vendor/autoload.php';

use Google\Cloud\Firestore\FirestoreClient;

$firestore = new FirestoreClient();

$collectionReference = $firestore->collection('Users');
$documentReference = $collectionReference->document($userId);
$snapshot = $documentReference->snapshot();

echo "Hello " . $snapshot['firstName'];


Cloud Firestore can be installed separately by requiring the google/cloud-firestore composer package:

$ composer require google/cloud-firestore

Cloud Spanner (GA)


require 'vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient();

$db = $spanner->connect('my-instance', 'my-database');

$userQuery = $db->execute('SELECT * FROM Users WHERE id = @id', [
    'parameters' => [
        'id' => $userId

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['firstName'];


Cloud Spanner can be installed separately by requiring the google/cloud-spanner composer package:

$ composer require google/cloud-spanner

Google BigQuery (GA)


require 'vendor/autoload.php';

use Google\Cloud\BigQuery\BigQueryClient;

$bigQuery = new BigQueryClient();

// Get an instance of a previously created table.
$dataset = $bigQuery->dataset('my_dataset');
$table = $dataset->table('my_table');

// Begin a job to import data from a CSV file into the table.
$loadJobConfig = $table->load(
    fopen('/data/my_data.csv', 'r')
$job = $table->runJob($loadJobConfig);

// Run a query and inspect the results.
$queryJobConfig = $bigQuery->query(
    'SELECT * FROM `my_project.my_dataset.my_table`'
$queryResults = $bigQuery->runQuery($queryJobConfig);

foreach ($queryResults as $row) {


Google BigQuery can be installed separately by requiring the google/cloud-bigquery composer package:

$ composer require google/cloud-bigquery

Google Bigtable (GA)


require 'vendor/autoload.php';

use Google\Cloud\Bigtable\BigtableClient;

$bigtable = new BigtableClient();
$table = $bigtable->table('my-instance', 'my-table');
$rows = $table->readRows();

foreach ($rows as $row) {
    print_r($row) . PHP_EOL;


Google Bigtable can be installed separately by requiring the google/cloud-bigtable composer package:

$ composer require google/cloud-bigtable

Google Cloud Datastore (GA)


require 'vendor/autoload.php';

use Google\Cloud\Datastore\DatastoreClient;

$datastore = new DatastoreClient();

// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = '';

// Update the entity
$bob['email'] = '';

// If you know the ID of the entity, you can look it up
$key = $datastore->key('Person', '12345328897844');
$entity = $datastore->lookup($key);


Google Cloud Datastore can be installed separately by requiring the google/cloud-datastore composer package:

$ composer require google/cloud-datastore

Google Cloud KMS (GA)

require __DIR__ . '/vendor/autoload.php';

use Google\ApiCore\ApiException;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\KeyRing;

$client = new KeyManagementServiceClient();

$projectId = 'example-project';
$location = 'global';

// Create a keyring
$keyRingId = 'example-keyring';
$locationName = $client::locationName($projectId, $location);
$keyRingName = $client::keyRingName($projectId, $location, $keyRingId);

try {
    $keyRing = $client->getKeyRing($keyRingName);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        $keyRing = new KeyRing();
        $client->createKeyRing($locationName, $keyRingId, $keyRing);

// Create a cryptokey
$keyId = 'example-key';
$keyName = $client::cryptoKeyName($projectId, $location, $keyRingId, $keyId);

try {
    $cryptoKey = $client->getCryptoKey($keyName);
} catch (ApiException $e) {
    if ($e->getStatus() === 'NOT_FOUND') {
        $cryptoKey = new CryptoKey();
        $cryptoKey = $client->createCryptoKey($keyRingName, $keyId, $cryptoKey);

// Encrypt and decrypt
$secret = 'My secret text';
$response = $client->encrypt($keyName, $secret);
$cipherText = $response->getCiphertext();

$response = $client->decrypt($keyName, $cipherText);

$plainText = $response->getPlaintext();

assert($secret === $plainText);


Google Cloud KMS can be installed separately by requiring the google/cloud-kms composer package:

$ composer require google/cloud-kms

Google Cloud Pub/Sub (GA)


require 'vendor/autoload.php';

use Google\Cloud\PubSub\PubSubClient;

$pubSub = new PubSubClient();

// Get an instance of a previously created topic.
$topic = $pubSub->topic('my_topic');

// Publish a message to the topic.
    'data' => 'My new message.',
    'attributes' => [
        'location' => 'Detroit'

// Get an instance of a previously created subscription.
$subscription = $pubSub->subscription('my_subscription');

// Pull all available messages.
$messages = $subscription->pull();

foreach ($messages as $message) {
    echo $message->data() . "\n";
    echo $message->attribute('location');


Google Cloud Pub/Sub can be installed separately by requiring the google/cloud-pubsub composer package:

$ composer require google/cloud-pubsub

Google Cloud Scheduler (GA)

require 'vendor/autoload.php';

use Google\Cloud\Scheduler\V1\AppEngineHttpTarget;
use Google\Cloud\Scheduler\V1\CloudSchedulerClient;
use Google\Cloud\Scheduler\V1\Job;
use Google\Cloud\Scheduler\V1\Job\State;

$client = new CloudSchedulerClient();
$projectId = '[MY_PROJECT_ID]';
$location = 'us-central1';
$parent = CloudSchedulerClient::locationName($projectId, $location);
$job = new Job([
    'name' => CloudSchedulerClient::jobName(
    'app_engine_http_target' => new AppEngineHttpTarget([
        'relative_uri' => '/'
    'schedule' => '* * * * *'
$client->createJob($parent, $job);

foreach ($client->listJobs($parent) as $job) {
        'Job: %s : %s' . PHP_EOL,


Google Cloud Scheduler can be installed separately by requiring the google/cloud-scheduler composer package:

$ composer require google/cloud-scheduler

Google Cloud Storage (GA)


require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();

$bucket = $storage->bucket('my_bucket');

// Upload a file to the bucket.
    fopen('/data/file.txt', 'r')

// Using Predefined ACLs to manage object permissions, you may
// upload a file and give read access to anyone with the URL.
    fopen('/data/file.txt', 'r'),
        'predefinedAcl' => 'publicRead'

// Download and store an object from the bucket locally.
$object = $bucket->object('file_backup.txt');

Stream Wrapper

require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();

$contents = file_get_contents('gs://my_bucket/file_backup.txt');


Google Cloud Storage can be installed separately by requiring the google/cloud-storage composer package:

$ composer require google/cloud-storage

Google Cloud Tasks (GA)


require_once __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Tasks\V2\CloudTasksClient;
use Google\Cloud\Tasks\V2\Queue;

$client = new CloudTasksClient();

$project = 'example-project';
$location = 'us-central1';
$queue = uniqid('example-queue-');
$queueName = $client::queueName($project, $location, $queue);

// Create a queue
$locationName = $client::locationName($project, $location);
$queue = new Queue([
    'name' => $queueName
$client->createQueue($locationName, $queue);

echo "$queueName created." . PHP_EOL;

// List queues
echo 'Listing the queues' . PHP_EOL;
$resp = $client->listQueues($locationName);
foreach ($resp->iterateAllElements() as $q) {
    echo $q->getName() . PHP_EOL;

// Delete the queue

Removal of pull queue

The past version (V2beta2) supported pull queues, but we removed the pull queue support from V2/V2beta3. For more details, read our documentation about the removal.


Google Cloud Tasks can be installed separately by requiring the google/cloud-tasks composer package:

$ composer require google/cloud-tasks

Google Cloud Translation (GA)


require 'vendor/autoload.php';

use Google\Cloud\Translate\V2\TranslateClient;

$translate = new TranslateClient([
    'key' => 'your_key'

// Translate text from english to french.
$result = $translate->translate('Hello world!', [
    'target' => 'fr'

echo $result['text'] . "\n";

// Detect the language of a string.
$result = $translate->detectLanguage('Greetings from Michigan!');

echo $result['languageCode'] . "\n";

// Get the languages supported for translation specifically for your target language.
$languages = $translate->localizedLanguages([
    'target' => 'en'

foreach ($languages as $language) {
    echo $language['name'] . "\n";
    echo $language['code'] . "\n";

// Get all languages supported for translation.
$languages = $translate->languages();

foreach ($languages as $language) {
    echo $language . "\n";


Google Cloud Translation can be installed separately by requiring the google/cloud-translate composer package:

$ composer require google/cloud-translate

Google Cloud Video Intelligence (GA)


require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\VideoIntelligence\V1\VideoIntelligenceServiceClient;
use Google\Cloud\VideoIntelligence\V1\Feature;

$videoIntelligenceServiceClient = new VideoIntelligenceServiceClient();

$inputUri = "gs://example-bucket/example-video.mp4";

$features = [
$operationResponse = $videoIntelligenceServiceClient->annotateVideo([
    'inputUri' => $inputUri,
    'features' => $features
if ($operationResponse->operationSucceeded()) {
    $results = $operationResponse->getResult();
    foreach ($results->getAnnotationResults() as $result) {
        echo 'Segment labels' . PHP_EOL;
        foreach ($result->getSegmentLabelAnnotations() as $labelAnnotation) {
            echo "Label: " . $labelAnnotation->getEntity()->getDescription()
                . PHP_EOL;
        echo 'Shot labels' . PHP_EOL;
        foreach ($result->getShotLabelAnnotations() as $labelAnnotation) {
            echo "Label: " . $labelAnnotation->getEntity()->getDescription()
                . PHP_EOL;
        echo 'Frame labels' . PHP_EOL;
        foreach ($result->getFrameLabelAnnotations() as $labelAnnotation) {
            echo "Label: " . $labelAnnotation->getEntity()->getDescription()
                . PHP_EOL;
} else {
    $error = $operationResponse->getError();
    echo "error: " . $error->getMessage() . PHP_EOL;



Cloud Video Intelligence can be installed separately by requiring the google/cloud-videointelligence composer package:

$ composer require google/cloud-videointelligence

Google Stackdriver Logging (GA)


require 'vendor/autoload.php';

use Google\Cloud\Logging\LoggingClient;

$logging = new LoggingClient();

// Get a logger instance.
$logger = $logging->logger('my_log');

// Write a log entry.
$logger->write('my message');

// List log entries from a specific log.
$entries = $logging->entries([
    'filter' => 'logName = projects/my_project/logs/my_log'

foreach ($entries as $entry) {
    echo $entry->info()['textPayload'] . "\n";


Google Stackdriver Logging can be installed separately by requiring the google/cloud-logging composer package:

$ composer require google/cloud-logging

Cloud AutoML (Beta)


require 'vendor/autoload.php';

use Google\Cloud\AutoMl\V1\AutoMlClient;
use Google\Cloud\AutoMl\V1\TranslationDatasetMetadata;

$autoMlClient = new AutoMlClient();
$formattedParent = $autoMlClient->locationName('[PROJECT]', '[LOCATION]');
$dataset = new Dataset([
    'display_name' => '[DISPLAY_NAME]',
    'translation_dataset_metadata' => new TranslationDatasetMetadata([
        'source_language_code' => 'en',
        'target_language_code' => 'es'
$response = $autoMlClient->createDataset($formattedParent, $dataset);


Cloud AutoML can be installed separately by requiring the google/cloud-automl composer package:

$ composer require google/cloud-firestore

Google Cloud Asset (Beta)


require_once __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Asset\V1\AssetServiceClient;
use Google\Cloud\Asset\V1\GcsDestination;
use Google\Cloud\Asset\V1\OutputConfig;

$objectPath = 'gs://your-bucket/cai-export';
// Now you need to change this with your project number (numeric id)
$project = 'example-project';

$client = new AssetServiceClient();

$gcsDestination = new GcsDestination(['uri' => $objectPath]);
$outputConfig = new OutputConfig(['gcs_destination' => $gcsDestination]);

$resp = $client->exportAssets("projects/$project", $outputConfig);


if ($resp->operationSucceeded()) {
    echo "The result is dumped to $objectPath successfully." . PHP_EOL;
} else {
    $error = $resp->getError();
    // handleError($error)


Cloud Asset Inventory can be installed separately by requiring the google/cloud-asset composer package:

$ composer require google/cloud-asset

Google Cloud Container (Beta)

require 'vendor/autoload.php';

use Google\Cloud\Container\V1\ClusterManagerClient;

$clusterManagerClient = new ClusterManagerClient();

$projectId = '[MY-PROJECT-ID]';
$zone = 'us-central1-a';

try {
    $clusters = $clusterManagerClient->listClusters($projectId, $zone);
    foreach ($clusters->getClusters() as $cluster) {
        print('Cluster: ' . $cluster->getName() . PHP_EOL);
} finally {


Google Cloud Container can be installed separately by requiring the google/cloud-container composer package:

$ composer require google/cloud-container

Google Cloud Dataproc (Beta)

require 'vendor/autoload.php';

use Google\Cloud\Dataproc\V1\JobControllerClient;
use Google\Cloud\Dataproc\V1\Job;
use Google\Cloud\Dataproc\V1\HadoopJob;
use Google\Cloud\Dataproc\V1\JobPlacement;

$projectId = '[MY_PROJECT_ID]';
$region = 'global';
$clusterName = '[MY_CLUSTER]';

$jobPlacement = new JobPlacement();

$hadoopJob = new HadoopJob();

$job = new Job();

$jobControllerClient = new JobControllerClient();
$submittedJob = $jobControllerClient->submitJob($projectId, $region, $job);


Google Cloud Dataproc can be installed separately by requiring the google/cloud-dataproc composer package:

$ composer require google/cloud-dataproc

Google Cloud Natural Language (Beta)


require 'vendor/autoload.php';

use Google\Cloud\Language\V1\AnnotateTextRequest\Features;
use Google\Cloud\Language\V1\Document;
use Google\Cloud\Language\V1\Document\Type;
use Google\Cloud\Language\V1\Entity\Type as EntityType;
use Google\Cloud\Language\V1\LanguageServiceClient;
use Google\Cloud\Language\V1\PartOfSpeech\Tag;

$client = new LanguageServiceClient([
    'credentials' => '/Users/dsupplee/Downloads/gcloud.json'

$document = new Document([
    'content' => 'Greetings from Michigan!',
    'type' => Type::PLAIN_TEXT
$features = new Features([
    'extract_document_sentiment' => true,
    'extract_entities' => true,
    'extract_syntax' => true

// Annotate the document.
$response = $client->annotateText($document, $features);

// Check the sentiment.
$sentimentScore = $response->getDocumentSentiment()

if ($sentimentScore > 0) {
    echo 'This is a positive message.' . PHP_EOL;

// Detect entities.
foreach ($response->getEntities() as $entity) {
        '[%s] %s',
    echo PHP_EOL;

// Parse the syntax.
foreach ($response->getTokens() as $token) {
    $speechTag = Tag::name($token->getPartOfSpeech()->getTag());

        '[%s] %s',
    echo PHP_EOL;


Google Cloud Natural Language can be installed separately by requiring the google/cloud-language composer package:

$ composer require google/cloud-language

Google Cloud OsLogin (Beta)

require 'vendor/autoload.php';

use Google\Cloud\OsLogin\V1\OsLoginServiceClient;

$osLoginServiceClient = new OsLoginServiceClient();
$userId = '[MY_USER_ID]';
$formattedName = $osLoginServiceClient->userName($userId);
$loginProfile = $osLoginServiceClient->getLoginProfile($formattedName);


Google Cloud OsLogin can be installed separately by requiring the google/cloud-oslogin composer package:

$ composer require google/cloud-oslogin

Google Cloud Speech (Beta)


require 'vendor/autoload.php';

use Google\Cloud\Speech\V1\RecognitionConfig\AudioEncoding;
use Google\Cloud\Speech\V1\RecognitionConfig;
use Google\Cloud\Speech\V1\StreamingRecognitionConfig;

$recognitionConfig = new RecognitionConfig();
$config = new StreamingRecognitionConfig();

$audioResource = fopen('path/to/audio.flac', 'r');

$responses = $speechClient->recognizeAudioStream($config, $audioResource);

foreach ($responses as $element) {
    // doSomethingWith($element);


Google Cloud Speech can be installed separately by requiring the google/cloud-speech composer package:

$ composer require google/cloud-speech

Google Cloud Text-to-Speech (Beta)

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;

$textToSpeechClient = new TextToSpeechClient();

$input = new SynthesisInput();
$input->setText('Japan\'s national soccer team won against Colombia!');
$voice = new VoiceSelectionParams();
$audioConfig = new AudioConfig();

$resp = $textToSpeechClient->synthesizeSpeech($input, $voice, $audioConfig);
file_put_contents('test.mp3', $resp->getAudioContent());


Google Cloud Text-to-Speech can be installed separately by requiring the google/cloud-text-to-speech composer package:

$ composer require google/cloud-text-to-speech

Google Cloud Vision (Beta)


require 'vendor/autoload.php';

use Google\Cloud\Vision\VisionClient;

$vision = new VisionClient();

// Annotate an image, detecting faces.
$image = $vision->image(
    fopen('/data/family_photo.jpg', 'r'),

$annotation = $vision->annotate($image);

// Determine if the detected faces have headwear.
foreach ($annotation->faces() as $key => $face) {
    if ($face->hasHeadwear()) {
        echo "Face $key has headwear.\n";


Google Cloud Vision can be installed separately by requiring the google/cloud-vision composer package:

$ composer require google/cloud-vision

Google DLP (Beta)


require 'vendor/autoload.php';

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;

$dlpServiceClient = new DlpServiceClient();
$infoTypesElement = (new InfoType())
$inspectConfig = (new InspectConfig())
$item = (new ContentItem())
    ->setValue('My email is');
$formattedParent = $dlpServiceClient

$response = $dlpServiceClient->inspectContent($formattedParent, [
    'inspectConfig' => $inspectConfig,
    'item' => $item

$findings = $response->getResult()

foreach ($findings as $finding) {
    print $finding->getInfoType()
        ->getName() . PHP_EOL;


Google DLP can be installed separately by requiring the google/cloud-dlp composer package:

$ composer require google/cloud-dlp

Google Stackdriver Error Reporting (Beta)


The Stackdriver Error Reporting client provides APIs allowing you to easily configure your application to send errors and exceptions automatically to Stackdriver, or to manually report and manage errors and statistics.

Reporting errors from your application:
require 'vendor/autoload.php';

use Google\Cloud\ErrorReporting\Bootstrap;
use Google\Cloud\Logging\LoggingClient;
use Google\Cloud\Core\Report\SimpleMetadataProvider;

$projectId = '[PROJECT]';
$service = '[SERVICE_NAME]';
$version = '[APP_VERSION]';

$logging = new LoggingClient();
$metadata = new SimpleMetadataProvider([], $projectId, $service, $version);
$psrLogger = $logging->psrLogger('error-log', [
    'metadataProvider' => $metadata

// Register the logger as a PHP exception and error handler.
// This will begin logging application exceptions and errors to Stackdriver.
Using the Error Reporting API:
require 'vendor/autoload.php';

use Google\Cloud\ErrorReporting\V1beta1\ReportErrorsServiceClient;
use Google\Cloud\ErrorReporting\V1beta1\ReportedErrorEvent;

$reportErrorsServiceClient = new ReportErrorsServiceClient();
$formattedProjectName = $reportErrorsServiceClient->projectName('[PROJECT]');
$event = new ReportedErrorEvent();

try {
    $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event);
} finally {


Google Stackdriver Error Reporting can be installed separately by requiring the google/cloud-errorreporting composer package:

$ composer require google/cloud-error-reporting

Google Stackdriver Monitoring (Beta)


require 'vendor/autoload.php';

use Google\Api\Metric;
use Google\Api\MonitoredResource;
use Google\Cloud\Monitoring\V3\MetricServiceClient;
use Google\Cloud\Monitoring\V3\Point;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\TimeSeries;
use Google\Cloud\Monitoring\V3\TypedValue;
use Google\Protobuf\Timestamp;

$metricServiceClient = new MetricServiceClient();
$formattedProjectName = $metricServiceClient->projectName($projectId);
$labels = [
    'instance_id' => $instanceId,
    'zone' => $zone,

$m = new Metric();

$r = new MonitoredResource();

$value = new TypedValue();

$timestamp = new Timestamp();

$interval = new TimeInterval();

$point = new Point();
$points = [$point];

$timeSeries = new TimeSeries();

try {
    $metricServiceClient->createTimeSeries($formattedProjectName, [$timeSeries]);
    print('Successfully submitted a time series' . PHP_EOL);
} finally {


Google Stackdriver Monitoring can be installed separately by requiring the google/cloud-monitoring composer package:

$ composer require google/cloud-monitoring

Dialogflow API (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Dialogflow\V2\EntityTypesClient;

$entityTypesClient = new EntityTypesClient();
$projectId = '[MY_PROJECT_ID]';
$entityTypeId = '[ENTITY_TYPE_ID]';
$formattedEntityTypeName = $entityTypesClient->entityTypeName($projectId, $entityTypeId);

$entityType = $entityTypesClient->getEntityType($formattedEntityTypeName);
foreach ($entityType->getEntities() as $entity) {
    printf('Entity value: %s' . PHP_EOL, $entity->getValue());
    print('Synonyms: ');
    foreach ($entity->getSynonyms() as $synonym) {
        print($synonym . "\t");


Dialogflow can be installed separately by requiring the google/cloud-dialogflow composer package:

$ composer require google/cloud-dialogflow

Google Cloud BigQuery Data Transfer (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\BigQuery\DataTransfer\V1\DataTransferServiceClient;

$dataTransferServiceClient = new DataTransferServiceClient();
$projectId = '[MY_PROJECT_ID]';
$location = 'us-central1';
$formattedLocation = $dataTransferServiceClient->locationName($projectId, $location);
$dataSources = $dataTransferServiceClient->listDataSources($formattedLocation);


Google Cloud BigQuery Data Transfer can be installed separately by requiring the google/cloud-bigquerydatatransfer composer package:

$ composer require google/cloud-bigquerydatatransfer

Google Cloud IoT (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Iot\V1\DeviceManagerClient;

$deviceManager = new DeviceManagerClient();

$projectId = '[MY_PROJECT_ID]';
$location = 'us-central1';
$registryId = '[MY_REGISTRY_ID]';
$registryName = $deviceManager->registryName($projectId, $location, $registryId);
$devices = $deviceManager->listDevices($registryName);
foreach ($devices->iterateAllElements() as $device) {
    printf('Device: %s : %s' . PHP_EOL,


Google Cloud IoT can be installed separately by requiring the google/cloud-iot composer package:

$ composer require google/cloud-iot

Google Cloud Redis (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Redis\V1\CloudRedisClient;

$client = new CloudRedisClient();

$projectId = '[MY_PROJECT_ID]';
$location = '-'; // The '-' wildcard refers to all regions available to the project for the listInstances method
$formattedLocationName = $client->locationName($projectId, $location);
$response = $client->listInstances($formattedLocationName);
foreach ($response->iterateAllElements() as $instance) {
    printf('Instance: %s : %s' . PHP_EOL,


Google Cloud Redis can be installed separately by requiring the google/cloud-redis composer package:

$ composer require google/cloud-redis

Google Cloud Security Command Center (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\SecurityCenter\V1\SecurityCenterClient;
use Google\Cloud\SecurityCenter\V1\Source;

$security = new SecurityCenterClient();
$parent = SecurityCenterClient::organizationName('[YOUR ORGANIZATION]');
$source = new Source([
    'name' => SecurityCenterClient::sourceName('[YOUR ORGANIZATION]', '[YOUR SOURCE]'),
    'displayName' => '[YOUR SOURCE]'

$res = $security->createSource($parent, $source);


Google Cloud Security Command Center can be installed separately by requiring the google/cloud-security-center composer package:

$ composer require google/cloud-security-center

Google Cloud Talent Solution (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Talent\V4beta1\Company;
use Google\Cloud\Talent\V4beta1\CompanyServiceClient;

$client = new CompanyServiceClient();
$response = $client->createCompany(
    new Company([
        'display_name' => 'Google, LLC',
        'external_id' => 1,
        'headquarters_address' => '1600 Amphitheatre Parkway, Mountain View, CA'


Google Cloud Talent Solution can be installed separately by requiring the google/cloud-talent composer package:

$ composer require google/cloud-talent

Google Stackdriver Debugger (Alpha)


use Google\Cloud\Debugger\DebuggerClient;

$debugger = new DebuggerClient();
$debuggee = $debugger->debugee();


Stackdriver Debugger can be installed separately by requiring the google/cloud-debugger composer package:

$ composer require google/cloud-debugger

Google Cloud Web Risk (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\WebRisk\V1beta1\ThreatType;
use Google\Cloud\WebRisk\V1beta1\WebRiskServiceV1Beta1Client;

$webrisk = new WebRiskServiceV1Beta1Client();

$uri = '';
$response = $webrisk->searchUris($uri, [

$threats = $response->getThreat();
if ($threats) {
    echo $uri . ' has the following threats:' . PHP_EOL;
    foreach ($threats->getThreatTypes() as $threat) {
        echo ThreatType::name($threat) . PHP_EOL;


Google Cloud Web Risk can be installed separately by requiring the google/cloud-web-risk composer package:

$ composer require google/cloud-web-risk

Google Cloud Web Security Scanner (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\WebSecurityScanner\V1beta\ScanConfig;
use Google\Cloud\WebSecurityScanner\V1beta\ScanConfig\UserAgent;
use Google\Cloud\WebSecurityScanner\V1beta\ScanRun\ExecutionState;
use Google\Cloud\WebSecurityScanner\V1beta\WebSecurityScannerClient;

$client = new WebSecurityScannerClient();
$scanConfig = $client->createScanConfig(
    new ScanConfig([
        'display_name' => 'Test Scan',
        'starting_urls' => ['https://[MY_APPLICATION_ID]'],
        'user_agent' => UserAgent::CHROME_LINUX
$scanRun = $client->startScanRun($scanConfig->getName());

echo 'Scan execution state: ' . ExecutionState::name($scanRun->getExecutionState()) . PHP_EOL;


Google Cloud Web Risk can be installed separately by requiring the google/cloud-web-risk composer package:

$ composer require google/cloud-web-security-scanner

Google Stackdriver Trace (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Trace\TraceClient;

$traceClient = new TraceClient();

// Create a Trace
$trace = $traceClient->trace();
$span = $trace->span([
    'name' => 'main'


// List recent Traces
foreach($traceClient->traces() as $trace) {


Stackdriver Trace can be installed separately by requiring the google/cloud-trace composer package:

$ composer require google/cloud-trace

Recommender (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\Recommender\V1\RecommenderClient;

$client = new RecommenderClient();

$recommendations = $client->listRecommendations(

foreach ($recommendations as $recommendation) {
        'Found recommendation: %s' . PHP_EOL,


Recommender can be installed separately by requiring the google/cloud-recommender composer package:

$ composer require google/cloud-recommender

Secret Manager (Alpha)


require 'vendor/autoload.php';

use Google\Cloud\SecretManager\V1beta1\Replication;
use Google\Cloud\SecretManager\V1beta1\Replication\Automatic;
use Google\Cloud\SecretManager\V1beta1\Secret;
use Google\Cloud\SecretManager\V1beta1\SecretManagerServiceClient;

$client = new SecretManagerServiceClient();

$secret = $client->createSecret(
        'secret' => new Secret([
            'replication' => new Replication([
                'automatic' => new Automatic()

    'Created secret: %s' . PHP_EOL,


Secret Manager can be installed separately by requiring the google/cloud-secret-manager composer package:

$ composer require google/cloud-secret-manager

Caching Access Tokens

By default the library will use a simple in-memory caching implementation, however it is possible to override this behavior by passing a PSR-6 caching implementation in to the desired client.

The following example takes advantage of Symfony's Cache Component.

require 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

// Please take the proper precautions when storing your access tokens in a cache no matter the implementation.
$cache = new ArrayAdapter();

$storage = new StorageClient([
    'authCache' => $cache

This library provides a PSR-6 implementation with the SystemV shared memory at Google\Auth\Cache\SysVCacheItemPool. This implementation is only available on *nix machines, but it's the one of the fastest implementations and you can share the cache among multiple processes. The following example shows how to use it.

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;
use Google\Auth\Cache\SysVCacheItemPool;

$cache = new SysVCacheItemPool();

$spanner = new SpannerClient([
    'authCache' => $cache


This library follows Semantic Versioning.

Please note it is currently under active development. Any release versioned 0.x.y is subject to backwards incompatible changes at any time.

GA: Libraries defined at a GA quality level are stable, and will not introduce backwards-incompatible changes in any minor or patch releases. We will address issues and requests with the highest priority. Please note, for any components which include generated clients the GA guarantee will only apply to clients which interact with stable services. For example, in a component which hosts V1 and V1beta1 generated clients, the GA guarantee will only apply to the V1 client as the service it interacts with is considered stable.

Beta: Libraries defined at a Beta quality level are expected to be mostly stable and we're working towards their release candidate. We will address issues and requests with a higher priority.

Alpha: Libraries defined at an Alpha quality level are still a work-in-progress and are more likely to get backwards-incompatible updates.


Contributions to this library are always welcome and highly encouraged.

See CONTRIBUTING for more information on how to get started.


Apache 2.0 - See LICENSE for more information.