Cloud Storage Client - Class Bucket (1.30.3)

Reference documentation and code samples for the Cloud Storage Client class Bucket.

Buckets are the basic containers that hold your data. Everything that you store in Google Cloud Storage must be contained in a bucket.

Example:

use Google\Cloud\Storage\StorageClient;

$storage = new StorageClient();

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

Methods

__construct

Parameters
NameDescription
connection Google\Cloud\Storage\Connection\ConnectionInterface

Represents a connection to Cloud Storage.

name string

The bucket's name.

info array

[optional] The bucket's metadata.

acl

Configure ACL for this bucket.

Example:

$acl = $bucket->acl();
Returns
TypeDescription
Google\Cloud\Storage\AclAn ACL instance configured to handle the bucket's access control policies.

defaultAcl

Configure default object ACL for this bucket.

Example:

$acl = $bucket->defaultAcl();
Returns
TypeDescription
Google\Cloud\Storage\AclAn ACL instance configured to handle the bucket's default object access control policies.

exists

Check whether or not the bucket exists.

Example:

if ($bucket->exists()) {
    echo 'Bucket exists!';
}
Parameter
NameDescription
options array

Configuration options.

Returns
TypeDescription
bool

upload

Upload your data in a simple fashion. Uploads will default to being resumable if the file size is greater than 5mb.

Example:

$object = $bucket->upload(
    fopen(__DIR__ . '/image.jpg', 'r')
);
// Upload an object in a resumable fashion while setting a new name for
// the object and including the content language.
$options = [
    'resumable' => true,
    'name' => '/images/new-name.jpg',
    'metadata' => [
        'contentLanguage' => 'en'
    ]
];

$object = $bucket->upload(
    fopen(__DIR__ . '/image.jpg', 'r'),
    $options
);
// Upload an object with a customer-supplied encryption key.
$key = base64_encode(openssl_random_pseudo_bytes(32)); // Make sure to remember your key.

$object = $bucket->upload(
    fopen(__DIR__ . '/image.jpg', 'r'),
    ['encryptionKey' => $key]
);
// Upload an object utilizing an encryption key managed by the Cloud Key Management Service (KMS).
$object = $bucket->upload(
    fopen(__DIR__ . '/image.jpg', 'r'),
    [
        'metadata' => [
            'kmsKeyName' => 'projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key'
        ]
    ]
);
Parameters
NameDescription
data string|resource|Psr\Http\Message\StreamInterface|null

The data to be uploaded.

options array

Configuration options.

↳ name string

The name of the destination. Required when data is of type string or null.

↳ resumable bool

Indicates whether or not the upload will be performed in a resumable fashion.

↳ validate bool|string

Indicates whether or not validation will be applied using md5 or crc32c hashing functionality. If enabled, and the calculated hash does not match that of the upstream server, the upload will be rejected. Available options are true, false, md5 and crc32. If true, either md5 or crc32c will be chosen based on your platform. If false, no validation hash will be sent. Choose either md5 or crc32 to force a hash method regardless of performance implications. In PHP versions earlier than 7.4, performance will be very adversely impacted by using crc32c unless you install the crc32c PHP extension. Defaults to true.

↳ chunkSize int

If provided the upload will be done in chunks. The size must be in multiples of 262144 bytes. With chunking you have increased reliability at the risk of higher overhead. It is recommended to not use chunking.

↳ uploadProgressCallback callable

If provided together with $resumable == true the given callable function/method will be called after each successfully uploaded chunk. The callable function/method will receive the number of uploaded bytes after each uploaded chunk as a parameter to this callable. It's useful if you want to create a progress bar when using resumable upload type together with $chunkSize parameter. If $chunkSize is not set the callable function/method will be called only once after the successful file upload.

↳ predefinedAcl string

Predefined ACL to apply to the object. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ metadata array

The full list of available options are outlined at the JSON API docs.

↳ metadata array

.metadata User-provided metadata, in key/value pairs.

↳ encryptionKey string

A base64 encoded AES-256 customer-supplied encryption key. If you would prefer to manage encryption utilizing the Cloud Key Management Service (KMS) please use the $metadata.kmsKeyName setting. Please note if using KMS the key ring must use the same location as the bucket.

↳ encryptionKeySHA256 string

Base64 encoded SHA256 hash of the customer-supplied encryption key. This value will be calculated from the encryptionKey on your behalf if not provided, but for best performance it is recommended to pass in a cached version of the already calculated SHA.

Returns
TypeDescription
Google\Cloud\Storage\StorageObject

uploadAsync

Asynchronously uploads an object.

Please note this method does not support resumable or streaming uploads.

Example:

$promise = $bucket->uploadAsync('Lorem Ipsum', ['name' => 'keyToData']);
$object = $promise->wait();
// Upload multiple objects to a bucket asynchronously.
$promises = [];
$objects = ['key1' => 'Lorem', 'key2' => 'Ipsum', 'key3' => 'Gypsum'];

foreach ($objects as $k => $v) {
    $promises[] = $bucket->uploadAsync($v, ['name' => $k])
        ->then(function (StorageObject $object) {
            echo $object->name() . PHP_EOL;
        }, function(\Exception $e) {
            throw new Exception('An error has occurred in the matrix.', null, $e);
        });
}

foreach ($promises as $promise) {
    $promise->wait();
}
Parameters
NameDescription
data string|resource|Psr\Http\Message\StreamInterface|null

The data to be uploaded.

options array

Configuration options.

↳ name string

The name of the destination. Required when data is of type string or null.

↳ validate bool|string

Indicates whether or not validation will be applied using md5 or crc32c hashing functionality. If enabled, and the calculated hash does not match that of the upstream server, the upload will be rejected. Available options are true, false, md5 and crc32. If true, either md5 or crc32c will be chosen based on your platform. If false, no validation hash will be sent. Choose either md5 or crc32 to force a hash method regardless of performance implications. In PHP versions earlier than 7.4, performance will be very adversely impacted by using crc32c unless you install the crc32c PHP extension. Defaults to true

↳ predefinedAcl string

Predefined ACL to apply to the object. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ metadata array

The full list of available options are outlined at the JSON API docs.

↳ metadata array

.metadata User-provided metadata, in key/value pairs.

↳ encryptionKey string

A base64 encoded AES-256 customer-supplied encryption key. If you would prefer to manage encryption utilizing the Cloud Key Management Service (KMS) please use the $metadata.kmsKeyName setting. Please note if using KMS the key ring must use the same location as the bucket.

↳ encryptionKeySHA256 string

Base64 encoded SHA256 hash of the customer-supplied encryption key. This value will be calculated from the encryptionKey on your behalf if not provided, but for best performance it is recommended to pass in a cached version of the already calculated SHA.

Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface<\google\cloud\storage\storageobject>

getResumableUploader

Get a resumable uploader which can provide greater control over the upload process. This is recommended when dealing with large files where reliability is key.

Example:

$uploader = $bucket->getResumableUploader(
    fopen(__DIR__ . '/image.jpg', 'r')
);

try {
    $object = $uploader->upload();
} catch (GoogleException $ex) {
    $resumeUri = $uploader->getResumeUri();
    $object = $uploader->resume($resumeUri);
}
Parameters
NameDescription
data string|resource|Psr\Http\Message\StreamInterface|null

The data to be uploaded.

options array

Configuration options.

↳ name string

The name of the destination. Required when data is of type string or null.

↳ validate bool

Indicates whether or not validation will be applied using md5 hashing functionality. If true and the calculated hash does not match that of the upstream server the upload will be rejected.

↳ predefinedAcl string

Predefined ACL to apply to the object. Acceptable values include "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ metadata array

The available options for metadata are outlined at the JSON API docs.

↳ encryptionKey string

A base64 encoded AES-256 customer-supplied encryption key. If you would prefer to manage encryption utilizing the Cloud Key Management Service (KMS) please use the $metadata['kmsKeyName'] setting. Please note if using KMS the key ring must use the same location as the bucket.

↳ encryptionKeySHA256 string

Base64 encoded SHA256 hash of the customer-supplied encryption key. This value will be calculated from the encryptionKey on your behalf if not provided, but for best performance it is recommended to pass in a cached version of the already calculated SHA.

↳ uploadProgressCallback callable

The given callable function/method will be called after each successfully uploaded chunk. The callable function/method will receive the number of uploaded bytes after each uploaded chunk as a parameter to this callable. It's useful if you want to create a progress bar when using resumable upload type together with $chunkSize parameter. If $chunkSize is not set the callable function/method will be called only once after the successful file upload.

Returns
TypeDescription
Google\Cloud\Core\Upload\ResumableUploader

getStreamableUploader

Get a streamable uploader which can provide greater control over the upload process. This is useful for generating large files and uploading the contents in chunks.

Example:

$uploader = $bucket->getStreamableUploader(
    'initial contents',
    ['name' => 'data.txt']
);

// finish uploading the item
$uploader->upload();
Parameters
NameDescription
data string|resource|Psr\Http\Message\StreamInterface

The data to be uploaded.

options array

Configuration options.

↳ name string

The name of the destination. Required when data is of type string or null.

↳ validate bool

Indicates whether or not validation will be applied using md5 hashing functionality. If true and the calculated hash does not match that of the upstream server the upload will be rejected.

↳ chunkSize int

If provided the upload will be done in chunks. The size must be in multiples of 262144 bytes. With chunking you have increased reliability at the risk of higher overhead. It is recommended to not use chunking.

↳ predefinedAcl string

Predefined ACL to apply to the object. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ metadata array

The available options for metadata are outlined at the JSON API docs.

↳ encryptionKey string

A base64 encoded AES-256 customer-supplied encryption key. If you would prefer to manage encryption utilizing the Cloud Key Management Service (KMS) please use the $metadata['kmsKeyName'] setting. Please note if using KMS the key ring must use the same location as the bucket.

↳ encryptionKeySHA256 string

Base64 encoded SHA256 hash of the customer-supplied encryption key. This value will be calculated from the encryptionKey on your behalf if not provided, but for best performance it is recommended to pass in a cached version of the already calculated SHA.

Returns
TypeDescription
Google\Cloud\Core\Upload\StreamableUploader

object

Lazily instantiates an object. There are no network requests made at this point. To see the operations that can be performed on an object please see Google\Cloud\Storage\StorageObject.

Example:

$object = $bucket->object('file.txt');
Parameters
NameDescription
name string

The name of the object to request.

options array

Configuration options.

↳ generation string

Request a specific revision of the object.

↳ encryptionKey string

A base64 encoded AES-256 customer-supplied encryption key. It will be neccesary to provide this when a key was used during the object's creation.

↳ encryptionKeySHA256 string

Base64 encoded SHA256 hash of the customer-supplied encryption key. This value will be calculated from the encryptionKey on your behalf if not provided, but for best performance it is recommended to pass in a cached version of the already calculated SHA.

Returns
TypeDescription
Google\Cloud\Storage\StorageObject

objects

Fetches all objects in the bucket.

Example:

// Get all objects beginning with the prefix 'photo'
$objects = $bucket->objects([
    'prefix' => 'photo',
    'fields' => 'items/name,nextPageToken'
]);

foreach ($objects as $object) {
    echo $object->name() . PHP_EOL;
}
Parameters
NameDescription
options array

Configuration options.

↳ delimiter string

Returns results in a directory-like mode. Results will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.

↳ maxResults int

Maximum number of results to return per request. Defaults to 1000.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

↳ pageToken string

A previously-returned page token used to resume the loading of results from a specific point.

↳ prefix string

Filter results with this prefix.

↳ projection string

Determines which properties to return. May be either "full" or "noAcl".

↳ versions bool

If true, lists all versions of an object as distinct results. Defaults to false.

↳ fields string

Selector which will cause the response to only return the specified fields.

Returns
TypeDescription
Google\Cloud\Storage\ObjectIterator<\google\cloud\storage\storageobject>

createNotification

Create a Cloud PubSub notification.

Please note, the desired topic must be given the IAM role of "pubsub.publisher" from the service account associated with the project which contains the bucket you would like to receive notifications from. Please see the example below for a programmatic example of achieving this.

Example:

// Update the permissions on the desired topic prior to creating the
// notification.
use Google\Cloud\Core\Iam\PolicyBuilder;
use Google\Cloud\PubSub\PubSubClient;

$pubSub = new PubSubClient();
$topicName = 'my-topic';
$serviceAccountEmail = $storage->getServiceAccount();
$topic = $pubSub->topic($topicName);
$iam = $topic->iam();
$updatedPolicy = (new PolicyBuilder($iam->policy()))
    ->addBinding('roles/pubsub.publisher', [
        "serviceAccount:$serviceAccountEmail"
    ])
    ->result();
$iam->setPolicy($updatedPolicy);

$notification = $bucket->createNotification($topicName);
// Use a fully qualified topic name.
$notification = $bucket->createNotification('projects/my-project/topics/my-topic');
// Provide a Topic object from the Cloud PubSub component.
use Google\Cloud\PubSub\PubSubClient;

$pubSub = new PubSubClient();
$topic = $pubSub->topic('my-topic');
$notification = $bucket->createNotification($topic);
// Supplying event types to trigger the notifications.
$notification = $bucket->createNotification('my-topic', [
    'event_types' => [
        'OBJECT_DELETE',
        'OBJECT_METADATA_UPDATE'
    ]
]);
Parameters
NameDescription
topic string|Google\Cloud\PubSub\Topic

The topic used to publish notifications.

options array

Configuration options.

↳ custom_attributes array

An optional list of additional attributes to attach to each Cloud PubSub message published for this notification subscription.

↳ event_types array

If present, only send notifications about listed event types. If empty, sent notifications for all event types. Acceptablue values include "OBJECT_FINALIZE", "OBJECT_METADATA_UPDATE", "OBJECT_DELETE" , "OBJECT_ARCHIVE".

↳ object_name_prefix string

If present, only apply this notification configuration to object names that begin with this prefix.

↳ payload_format string

The desired content of the Payload. Acceptable values include "JSON_API_V1", "NONE". Defaults to "JSON_API_V1".

Returns
TypeDescription
Google\Cloud\Storage\Notification

notification

Lazily instantiates a notification. There are no network requests made at this point. To see the operations that can be performed on a notification please see Google\Cloud\Storage\Notification.

Example:

$notification = $bucket->notification('4582');
Parameter
NameDescription
id string

The ID of the notification to access.

Returns
TypeDescription
Google\Cloud\Storage\Notification

notifications

Fetches all notifications associated with this bucket.

Example:

$notifications = $bucket->notifications();

foreach ($notifications as $notification) {
    echo $notification->id() . PHP_EOL;
}
Parameters
NameDescription
options array

Configuration options.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

Returns
TypeDescription
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\storage\notification>

delete

Delete the bucket.

Example:

$bucket->delete();
Parameters
NameDescription
options array

Configuration options.

↳ ifMetagenerationMatch string

If set, only deletes the bucket if its metageneration matches this value.

↳ ifMetagenerationNotMatch string

If set, only deletes the bucket if its metageneration does not match this value.

Returns
TypeDescription
void

update

Update the bucket. Upon receiving a result the local bucket's data will be updated.

Example:

// Enable logging on an existing bucket.
$bucket->update([
    'logging' => [
        'logBucket' => 'myBucket',
        'logObjectPrefix' => 'prefix'
    ]
]);
Parameters
NameDescription
options array

Configuration options.

↳ ifMetagenerationMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.

↳ ifMetagenerationNotMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.

↳ predefinedAcl string

Predefined ACL to apply to the bucket. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ predefinedDefaultObjectAcl string

Apply a predefined set of default object access controls to this bucket. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ projection string

Determines which properties to return. May be either "full" or "noAcl".

↳ fields string

Selector which will cause the response to only return the specified fields.

↳ acl array

Access controls on the bucket.

↳ cors array

The bucket's Cross-Origin Resource Sharing (CORS) configuration.

↳ defaultObjectAcl array

Default access controls to apply to new objects when no ACL is provided.

↳ lifecycle array|Lifecycle

The bucket's lifecycle configuration.

↳ logging array

The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.

↳ storageClass string

The bucket's storage class. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Acceptable values include the following strings: "STANDARD", "NEARLINE", "COLDLINE" and "ARCHIVE". Legacy values including "MULTI_REGIONAL", "REGIONAL" and "DURABLE_REDUCED_AVAILABILITY" are also available, but should be avoided for new implementations. For more information, refer to the Storage Classes documentation. Defaults to "STANDARD".

↳ autoclass array

The bucket's autoclass configuration. Buckets can have either StorageClass OLM rules or Autoclass, but not both. When Autoclass is enabled on a bucket, adding StorageClass OLM rules will result in failure.

↳ versioning array

The bucket's versioning configuration.

↳ website array

The bucket's website configuration.

↳ billing array

The bucket's billing configuration.

↳ billing bool

.requesterPays When true, requests to this bucket and objects within it must provide a project ID to which the request will be billed.

↳ labels array

The Bucket labels. Labels are represented as an array of keys and values. To remove an existing label, set its value to null.

↳ encryption array

Encryption configuration used by default for newly inserted objects.

↳ encryption string

.defaultKmsKeyName A Cloud KMS Key used to encrypt objects uploaded into this bucket. Should be in the format projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key. Please note the KMS key ring must use the same location as the bucket.

↳ defaultEventBasedHold bool

When true, newly created objects in this bucket will be retained indefinitely until an event occurs, signified by the hold's release.

↳ retentionPolicy array

Defines the retention policy for a bucket. In order to lock a retention policy, please see Google\Cloud\Storage\Google\Cloud\Storage\Bucket::lockRetentionPolicy().

↳ retentionPolicy int

.retentionPeriod Specifies the duration that objects need to be retained, in seconds. Retention duration must be greater than zero and less than 100 years.

↳ iamConfiguration array

The bucket's IAM configuration.

↳ iamConfiguration bool

.bucketPolicyOnly.enabled this is an alias for $iamConfiguration.uniformBucketLevelAccess.

↳ iamConfiguration bool

.uniformBucketLevelAccess.enabled If set and true, access checks only use bucket-level IAM policies or above. When enabled, requests attempting to view or manipulate ACLs will fail with error code 400. NOTE: Before using Uniform bucket-level access, please review the feature documentation, as well as Should You Use uniform bucket-level access

↳ iamConfiguration string

.publicAccessPrevention The bucket's Public Access Prevention configuration. Currently, 'inherited' and 'enforced' are supported. defaults to inherited. For more details, see Public Access Prevention.

Returns
TypeDescription
array

compose

Composes a set of objects into a single object.

Please note that all objects to be composed must come from the same bucket.

Example:

$sourceObjects = ['log1.txt', 'log2.txt'];
$singleObject = $bucket->compose($sourceObjects, 'combined-logs.txt');
// Use an instance of StorageObject.
$sourceObjects = [
    $bucket->object('log1.txt'),
    $bucket->object('log2.txt')
];

$singleObject = $bucket->compose($sourceObjects, 'combined-logs.txt');
Parameters
NameDescription
sourceObjects string[]|array<Google\Cloud\Storage\StorageObject>

The objects to compose.

name string

The name of the composed object.

options array

Configuration options.

↳ predefinedAcl string

Predefined ACL to apply to the composed object. Acceptable values include, "authenticatedRead", "bucketOwnerFullControl", "bucketOwnerRead", "private", "projectPrivate", and "publicRead".

↳ metadata array

Metadata to apply to the composed object. The available options for metadata are outlined at the JSON API docs.

↳ ifGenerationMatch string

Makes the operation conditional on whether the object's current generation matches the given value.

↳ ifMetagenerationMatch string

Makes the operation conditional on whether the object's current metageneration matches the given value.

Returns
TypeDescription
Google\Cloud\Storage\StorageObject

info

Retrieves the bucket's details. If no bucket data is cached a network request will be made to retrieve it.

Example:

$info = $bucket->info();
echo $info['location'];
Parameters
NameDescription
options array

Configuration options.

↳ ifMetagenerationMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.

↳ ifMetagenerationNotMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.

↳ projection string

Determines which properties to return. May be either "full" or "noAcl".

Returns
TypeDescription
array

reload

Triggers a network request to reload the bucket's details.

Example:

$bucket->reload();
$info = $bucket->info();
echo $info['location'];
Parameters
NameDescription
options array

Configuration options.

↳ ifMetagenerationMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.

↳ ifMetagenerationNotMatch string

Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.

↳ projection string

Determines which properties to return. May be either "full" or "noAcl".

Returns
TypeDescription
array

name

Retrieves the bucket's name.

Example:

echo $bucket->name();
Returns
TypeDescription
string

lifecycle

Retrieves a fresh lifecycle builder. If a lifecyle configuration already exists on the target bucket and this builder is used, it will fully replace the configuration with the rules provided by this builder.

This builder is intended to be used in tandem with Google\Cloud\Storage\Google\Cloud\Storage\StorageClient::createBucket() and Google\Cloud\Storage\Google\Cloud\Storage\Bucket::update().

Example:

use Google\Cloud\Storage\Bucket;

$lifecycle = Bucket::lifecycle()
    ->addDeleteRule([
        'age' => 50,
        'isLive' => true
    ]);
$bucket->update([
    'lifecycle' => $lifecycle
]);
Parameter
NameDescription
lifecycle array

[optional] A lifecycle configuration. Please see here for the expected structure.

Returns
TypeDescription
Google\Cloud\Storage\Lifecycle

currentLifecycle

Retrieves a lifecycle builder preconfigured with the lifecycle rules that already exists on the bucket. Use this if you want to make updates to an existing configuration without removing existing rules, as would be the case when using Google\Cloud\Storage\Bucket::lifecycle().

This builder is intended to be used in tandem with Google\Cloud\Storage\Google\Cloud\Storage\StorageClient::createBucket() and Google\Cloud\Storage\Google\Cloud\Storage\Bucket::update().

Please note, this method may trigger a network request in order to fetch the existing lifecycle rules from the server.

Example:

$lifecycle = $bucket->currentLifecycle()
    ->addDeleteRule([
        'age' => 50,
        'isLive' => true
    ]);
$bucket->update([
    'lifecycle' => $lifecycle
]);
// Iterate over existing rules.
$lifecycle = $bucket->currentLifecycle();

foreach ($lifecycle as $rule) {
    print_r($rule);
}
Parameter
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
Google\Cloud\Storage\Lifecycle

isWritable

Returns whether the bucket with the given file prefix is writable.

Tries to create a temporary file as a resumable upload which will not be completed (and cleaned up by GCS).

Parameter
NameDescription
file string

[optional] File to try to write.

Returns
TypeDescription
bool

iam

Manage the IAM policy for the current Bucket.

To request a policy with conditions, pass an array with '[requestedPolicyVersion => 3]' as argument to the policy() and reload() methods.

Example:

$iam = $bucket->iam();

// Returns the stored policy, or fetches the policy if none exists.
$policy = $iam->policy(['requestedPolicyVersion' => 3]);

// Fetches a policy from the server.
$policy = $iam->reload(['requestedPolicyVersion' => 3]);
Returns
TypeDescription
Google\Cloud\Core\Iam\Iam

lockRetentionPolicy

Locks a provided retention policy on this bucket. Upon receiving a result, the local bucket's data will be updated.

Please note that in order for this call to succeed, the applicable metageneration value will need to be available. It can either be supplied explicitly through the ifMetagenerationMatch option or detected for you by ensuring a value is cached locally (by calling Google\Cloud\Storage\Google\Cloud\Storage\Bucket::reload() or Google\Cloud\Storage\Google\Cloud\Storage\Bucket::info(), for example).

Example:

// Set a retention policy.
$bucket->update([
    'retentionPolicy' => [
        'retentionPeriod' => 604800 // One week in seconds.
    ]
]);
// Lock in the policy.
$info = $bucket->lockRetentionPolicy();
$retentionPolicy = $info['retentionPolicy'];

// View the time from which the policy was enforced and effective. (RFC 3339 format)
echo $retentionPolicy['effectiveTime'] . PHP_EOL;

// View whether or not the retention policy is locked. This will be
// `true` after a successful call to `lockRetentionPolicy`.
echo $retentionPolicy['isLocked'];
Parameters
NameDescription
options array

Configuration options.

↳ ifMetagenerationMatch string

Only locks the retention policy if the bucket's metageneration matches this value. If not provided the locally cached metageneration value will be used, otherwise an exception will be thrown.

Returns
TypeDescription
array

signedUrl

Create a Signed URL listing objects in this bucket.

Example:

$url = $bucket->signedUrl(time() + 3600);
// Use V4 Signing
$url = $bucket->signedUrl(time() + 3600, [
    'version' => 'v4'
]);
Parameters
NameDescription
expires Google\Cloud\Core\Timestamp|DateTimeInterface|int

Specifies when the URL will expire. May provide an instance of {@see \Google\Cloud\Storage\Google\Cloud\Core\Timestamp}, http://php.net/datetimeimmutable, or a UNIX timestamp as an integer.

options array

Configuration Options.

↳ cname string

The CNAME for the bucket, for instance https://cdn.example.com. Defaults to https://storage.googleapis.com.

↳ contentMd5 string

The MD5 digest value in base64. If you provide this, the client must provide this HTTP header with this same value in its request. If provided, take care to always provide this value as a base64 encoded string.

↳ contentType string

If you provide this value, the client must provide this HTTP header set to the same value.

↳ forceOpenssl bool

If true, OpenSSL will be used regardless of whether phpseclib is available. Defaults to false.

↳ headers array

If additional headers are provided, the server will check to make sure that the client provides matching values. Provide headers as a key/value array, where the key is the header name, and the value is an array of header values. Headers with multiple values may provide values as a simple array, or a comma-separated string. For a reference of allowed headers, see Reference Headers. Header values will be trimmed of leading and trailing spaces, multiple spaces within values will be collapsed to a single space, and line breaks will be replaced by an empty string. V2 Signed URLs may not provide x-goog-encryption-key or x-goog-encryption-key-sha256 headers.

↳ keyFile array

Keyfile data to use in place of the keyfile with which the client was constructed. If $options.keyFilePath is set, this option is ignored.

↳ keyFilePath string

A path to a valid keyfile to use in place of the keyfile with which the client was constructed.

↳ scopes string|array

One or more authentication scopes to be used with a key file. This option is ignored unless $options.keyFile or $options.keyFilePath is set.

↳ queryParams array

Additional query parameters to be included as part of the signed URL query string. For allowed values, see Reference Headers.

↳ version string

One of "v2" or "v4". Defaults to* "v2".

Returns
TypeDescription
string

generateSignedPostPolicyV4

Create a signed upload policy for uploading objects.

This method generates and signs a policy document. You can use policy documents to allow visitors to a website to upload files to Google Cloud Storage without giving them direct write access.

Google Cloud PHP does not support v2 post policies.

Example:

$policy = $bucket->generateSignedPostPolicyV4($objectName, new \DateTime('tomorrow'), [
    'conditions' => [
        ['content-length-range', 0, 255]
    ],
    'fields' => [
         'x-goog-meta-hello' => 'world',
         'success_action_redirect' => 'https://google.com'
    ]
]);

echo '<form action="' . $policy['url'] . '" method="post" enctype="multipart/form-data">';
foreach ($policy['fields'] as $name => $value) {
    echo '<input type="hidden" name="' . $name . '" value="' . $value . '">';
}

echo 'Upload a file!<br>';
echo '<input type="file" name="file">';
echo '<button type="submit">Submit!</button>';
echo '</form>';
Parameters
NameDescription
objectName string

The path to the file in Google Cloud Storage, relative to the bucket.

expires Google\Cloud\Core\Timestamp|DateTimeInterface|int

Specifies when the URL will expire. May provide an instance of {@see \Google\Cloud\Storage\Google\Cloud\Core\Timestamp}, http://php.net/datetimeimmutable, or a UNIX timestamp as an integer.

options array

Configuration options

↳ bucketBoundHostname string

The hostname for the bucket, for instance cdn.example.com. May be used for Google Cloud Load Balancers or for custom bucket CNAMEs. Defaults to storage.googleapis.com.

↳ conditions array

A list of arrays containing policy matching conditions (e.g. eq, starts-with, content-length-range).

↳ fields array

Additional form fields (do not include x-goog-signature, file, policy or fields with an x-ignore prefix), given as key/value pairs.

↳ forceOpenssl bool

If true, OpenSSL will be used regardless of whether phpseclib is available. Defaults to false.

↳ keyFile array

Keyfile data to use in place of the keyfile with which the client was constructed. If $options.keyFilePath is set, this option is ignored.

↳ keyFilePath string

A path to a valid Keyfile to use in place of the keyfile with which the client was constructed.

↳ scheme string

Either http or https. Only used if a custom hostname is provided via $options.bucketBoundHostname. If a custom bucketBoundHostname is provided, defaults to http. In all other cases, defaults to https.

↳ scopes string|array

One or more authentication scopes to be used with a key file. This option is ignored unless $options.keyFile or $options.keyFilePath is set.

↳ virtualHostedStyle bool

If true, URL will be of form mybucket.storage.googleapis.com. If false, storage.googleapis.com/mybucket. Defaults to false.

Returns
TypeDescription
arrayAn associative array, containing (string) `uri` and (array) `fields` keys.

Constants

NOTIFICATION_TEMPLATE

Value: '//pubsub.googleapis.com/%s'

TOPIC_TEMPLATE

Value: 'projects/%s/topics/%s'

TOPIC_REGEX

Value: '/projects\\/[^\\/]*\\/topics\\/(.*)/'