Cloud Storage Client - Class Bucket (1.36.1)

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');

Namespace

Google \ Cloud \ Storage

Methods

__construct

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

Represents a connection to Cloud Storage. This object is created by StorageClient, and should not be instantiated outside of this client.

name string

The bucket's name.

info array

[optional] The bucket's metadata.

acl

Returns
TypeDescription
Google\Cloud\Storage\AclAn ACL instance configured to handle the bucket's access control policies.

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

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".

↳ retention array

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

↳ retention string

.retainUntilTime The earliest time in RFC 3339 UTC "Zulu" format that the object can be deleted or replaced. This is the retention configuration set for this object.

↳ retention string

.mode The mode of the retention configuration, which can be either "Unlocked" or "Locked".

↳ 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

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

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

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

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.

↳ matchGlob string

A glob pattern to filter results. The string value must be UTF-8 encoded. See: https://cloud.google.com/storage/docs/json_api/v1/objects/list#list-object-glob

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

createNotification

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

Parameter
NameDescription
id string

The ID of the notification to access.

Returns
TypeDescription
Google\Cloud\Storage\Notification

notifications

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

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

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. For more information, refer to Storage Autoclass

↳ 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\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

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

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

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

currentLifecycle

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

Returns
TypeDescription
Google\Cloud\Core\Iam\Iam

lockRetentionPolicy

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

See also:

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

Specifies when the URL will expire. May provide an instance of 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

See also:

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 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.

static::lifecycle

Parameter
NameDescription
lifecycle array

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

Returns
TypeDescription
Google\Cloud\Storage\Lifecycle

Constants

NOTIFICATION_TEMPLATE

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

TOPIC_TEMPLATE

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

TOPIC_REGEX

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