Bucket management
A bucket serves as both a namespace within BOS and a management entity for advanced features like billing, permission control, and log recording.
- Bucket names are globally unique across all regions and cannot be changed after creation.
Description:
- Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md). The corresponding relationship between BOS regions and endpoints can be found in Access Domain Name Description.
- Each item stored in BOS is required to reside within a bucket.
- Users can create up to 100 buckets, with no limits on the number or total size of objects stored in each bucket. Data scalability is automatically managed by the system, so users need not worry about capacity limits.
Bucket permission management
Set bucket access permissions
The following code sets the bucket's permission to private:
1use BaiduBce\Services\Bos\CannedAcl;
2$client->setBucketCannedAcl($bucket, CannedAcl::ACL_PRIVATE);
Among them, three parameters are encapsulated in CannedAcl.php: ACL_PRIVATE, ACL_PUBLIC_READ, ACL_PUBLIC_READ_WRITE, and their corresponding permissions are: private, public-read, public-read-write respectively. For details about permission, refer to BOS API Documentation - [Permission Control Using CannedAcl](BOS/API Reference/Access control.md#Permission control by CannedAcl).
Set access permissions for a specific user on the bucket
BOS provides the setBucketAcl method to set the access permissions of specified users to the bucket, and you can refer to the following code to implement it:
1$my_acl = array(
2 array(
3 'grantee' => array(
4 array(
5 'id' => '7f34788d02a64a9c98f85600567d98a7',
6 ),
7 array(
8 'id' => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
9 ),
10 ),
11 'permission' => array('FULL_CONTROL'),
12 ),
13);
14$client->setBucketAcl($bucket, $my_acl);
Note:
- The permission settings in Permission include three values:
READ,WRITE,FULL_CONTROL, which correspond to relevant permissions respectively. For details, refer to BOS API Documentation - [Permission Control via Uploading ACL Files](BOS/API Reference/Access control.md#Permission control by uploading ACL files).- When specifying two or more grantees, refer to the format shown in the example above. Merging arrays will result in an error.
Set more bucket access permissions
- Set anti-leech through referer allow list
1$my_acl = array(
2 array(
3 'grantee' => array(
4 array(
5 'id' => '7f34788d02a64a9c98f85600567d98a7',
6 ),
7 ),
8 'permission' => array('FULL_CONTROL'),
9 'condition' => array(
10 'referer' => array(
11 'stringLike' => array('http://www.abc.com/*'),
12 'stringEquals' => array('http://www.abc.com'),
13 ),
14 ),
15 ),
16);
17$client->setBucketAcl($bucket, $my_acl);
- Restrict client IP access, only allow some client IPs to access
1$my_acl = array(
2 array(
3 'grantee' => array(
4 array(
5 'id' => '7f34788d02a64a9c98f85600567d98a7',
6 ),
7 ),
8 'permission' => array('FULL_CONTROL'),
9 'condition' => array(
10 'ipAddress' => array("192.168.0.0/16"),
11 ),
12 ),
13);
14$client->setBucketAcl($bucket, $my_acl);
Set STS temporary token permissions
For temporary access identities created through STS, administrators can also set specific permissions. For an introduction to STS and how to set temporary permissions, please refer to [Temporary Authorization Access](BOS/API Reference/Access control.md#Temporary authorized access).
For setting STS temporary token permissions using the BOS PHP SDK, you can refer to [Creating BosClient with STS](BOS/SDK/PHP-SDK/Initialization.md#Create a BosClient with STS)
View bucket permissions
The following code can be used to view the bucket permissions:
1$response = $client->getBucketAcl($bucket);
The parameters available for calling in the resolution class returned by the getBucketAcl method are as follows:
| Parameters | Description |
|---|---|
| owner | Bucket owner information |
| id | User ID of bucket owner |
| acl | Identify the permission list of the bucket |
| grantee | Identify the grantee |
| -id | Authorized person ID |
| permission | Identify the grantee permissions |
View the region to which a bucket belongs
Bucket Location refers to Bucket Region. For details on regions supported by Baidu AI Cloud, refer to [Region Selection Guide](Reference/Region Selection Instructions/Region.md).
The following code can retrieve the bucket's location information:
1$client->getBucketLocation($bucketName);
Create Bucket
The following code can be used to create a bucket:
1$bucketName = "your_bucket";
2 //Whether the bucket exists, if not, create the bucket
3$exist = $client->doesBucketExist($bucketName);
4if(!$exist){
5 $client->createBucket($bucketName);
6}
Note: Since the bucket name is unique across all regions, it is necessary to ensure that the bucketName is not the same as the BucketName on all other regions.
Bucket naming follows the following conventions:
- Only lowercase letters, numbers, and hyphens (-) are allowed.
- Must start with a lowercase letter or a number.
- Length should range between 4-63 bytes.
The bucket created using the above example has private read-write permissions and a Standard storage class. Users can customize the bucket permissions and storage class when creating a bucket in the console.
List buckets
The following code can list all buckets of a user:
1$response = $client->listBuckets();
2foreach ($response->buckets as $bucket) {
3 print $bucket->name;
4}
Delete bucket
Delete specified bucket
The following code can be used to delete a bucket:
1$bucketName = "your_bucket";
2$client->deleteBucket($bucketName);
Note:
- Before deletion, ensure that all objects and any unfinished multipart uploads in the bucket have been fully removed. Otherwise, the deletion will fail.
- Before deleting a bucket, verify that Cross-Region Replication (CRR) is not enabled for the bucket, and that it is neither the source nor target bucket in any CRR rules. Otherwise, the deletion will fail.
Delete all buckets
By combining the deleteBucket and listBuckets functions, all Buckets can be deleted. The reference code is as follows:
1 //List all buckets
2 $response = $client->listBuckets();
3 //Traverse and delete all buckets
4 foreach ($response->buckets as $bucket) {
5 $marker = null;
6 while (true) {
7 $options = array();
8 if ($marker !== null) {
9 $options[BosOptions::MARKER] = $marker;
10 }
11 $response = $client->listObjects($bucket->name, $options);
12 foreach ($response->contents as $object) {
13 $client->deleteObject($bucket->name, $object->key);
14 }
15 if ($response->isTruncated) {
16 $marker = $response->nextMarker;
17 } else {
18 break;
19 }
20 }
21 $client->deleteBucket($bucket->name);
22 }
Check if bucket exists
If users need to determine whether a bucket exists, the following code can achieve this:
1$client->doesBucketExist($bucketName);
Bucket data synchronization
Bucket data synchronization enables automatic synchronization of data across different buckets and supports custom synchronization rules. The data is categorized into stock data and incremental data. The usage is as follows:
Create data synchronization
1 $replication_rule = array(
2 'status' => 'enabled',
3 'replicateDeletes' => 'enabled',
4 'id' => 'sample'
5 );
6 $replication_rule['resource'][0] = $raw_bucket . "/*";
7 $replication_rule['destination']['bucket'] = $target_bucket;
8 $replication_rule['replicateHistory']['bucket'] = $target_bucket;
9 $bj_client->putBucketReplication($raw_bucket, $replication_rule);
Get bucket information for data synchronization
1$response = $bj_client->getBucketReplication($raw_bucket);
Delete data synchronization replication configuration
1$response = $bj_client->deleteBucketReplication($raw_bucket);
Get the progress status of bucket data synchronization
1$response = $bj_client->getBucketReplicationProgress($raw_bucket);
Bucket lifecycle management
Data has a lifecycle, spanning from creation to archiving and eventually deletion, which forms a complete cycle. Data is frequently accessed and read in its early stages, cools down and gets archived over time, and is ultimately deleted. Lifecycle management in object storage services helps users automate the management of data lifecycle. It is generally useful for the following situations:
- Automatically archive or delete data when it reaches a specified age.
- Perform specific operations at predefined times.
Create a new lifecycle configuration
The following code creates a new lifecycle configuration
1$lifecycle_rule = array(
2 array(
3 'id' => 'rule-id0',
4 'status' => 'enabled',
5 'resource' => array(
6 $this->bucket.'/prefix/*',
7 ),
8 'condition' => array(
9 'time' => array(
10 'dateGreaterThan' => '2016-09-07T00:00:00Z',
11 ),
12 ),
13 'action' => array(
14 'name' => 'DeleteObject',
15 )
16 ),
17 array(
18 'id' => 'rule-id1',
19 'status' => 'disabled',
20 'resource' => array(
21 $this->bucket.'/prefix/*',
22 ),
23 'condition' => array(
24 'time' => array(
25 'dateGreaterThan' => '2016-09-07T00:00:00Z',
26 ),
27 ),
28 'action' => array(
29 'name' => 'Transition',
30 'storageClass' => 'COLD',
31 ),
32 ),
33);
34 // Set lifecycle rules
35$client->putBucketLifecycle($bucket, $lifecycle_rule);
Note:
- Only the bucket owner with full permissions can carry out this operation.
- "resource" indicates resources to which the rules apply. Example: To apply to objects in samplebucket with the
prefix/:samplebucket/prefix/*; to apply to all objects in samplebucket:samplebucket/*.
For detailed explanations of parameters related to the lifecycle management function and configuration precautions, please refer to [PutBucketLifecycle API](BOS/API Reference/Bucket-Related Interface/Lifecycle/PutBucketLifecycle.md)
Read the lifecycle configuration of the bucket
The following code can read the lifecycle configuration of the bucket
1$response = $client->getBucketLifecycle($bucket);
Delete bucket lifecycle
The following code can delete the lifecycle of the bucket:
1$client->deleteBucketLifecycle($bucket);
Bucket cross-origin resource access
Cross-Origin Resource Sharing (CORS) allows web-based applications to access resources outside their current domain. BOS provides APIs to help developers manage cross-origin access permissions effectively.
Set CORS rules
The following code sets a CORS rule:
1$cors_rule = array(
2 array(
3 'allowedOrigins' => array(
4 'http://www.example.com',
5 'www.example2.com'
6 ),
7 'allowedMethods' => array(
8 'GET',
9 'HEAD'
10 ),
11 'allowedHeaders' => array(
12 'Authorization'
13 ),
14 'allowedExposeHeaders' => array(
15 'user-custom-expose-header'
16 ),
17 'maxAgeSeconds' => 3600
18 ),
19 array(
20 'allowedOrigins' => array(
21 'http://www.example3.com'
22 ),
23 'allowedMethods' => array(
24 'GET',
25 'PUT'
26 ),
27 'allowedHeaders' => array(
28 'x-bce-test'
29 ),
30 'allowedExposeHeaders' => array(
31 'user-custom-expose-header'
32 ),
33 'maxAgeSeconds' => 3600
34 )
35);
36$client->putBucketCors($bucket, $cors_rule);
Note:
- If an existing rule is found, it will overwrite the original rule.
- Only the bucket owner or users granted FULL_CONTROL permissions can set bucket CORS. If the necessary permissions are not granted, the server will return a 403 Forbidden error with the AccessDenied code.
For a detailed explanation of the parameters related to CORS rules, please refer to [PutBucketCors API](BOS/API Reference/Bucket-Related Interface/Cross-Origin Access/PutBucketCors.md)
Get the CORS rules of bucket
The following code can get the CORS configuration of the bucket:
1$response = $client->getBucketCors($bucket);
Disable the bucket CORS function and clear all rules
The following code can disable the CORS function of the bucket and clear all rules:
1$client->deleteBucketCors($bucket);
Bucket server-side encryption
BOS allows users to include the HTTP header x-bce-server-side-encryption in upload and copy requests (e.g., PutObject, PostObject, InitiateMultipartUpload, AppendObject, FetchObject, CopyObject) to specify the encryption algorithm (currently only AES256 is supported), ensuring effective data security.
Enable bucket server-side encryption
The following code can enable the bucket server-side encryption function
1$client->putBucketEncryption($bucket, 'AES256');
Get bucket server-side encryption information
The following code can get information related to bucket server-side encryption, including encryption algorithms, etc.
1$response = $client->getBucketEncryption($bucket);
Disable bucket server-side encryption
The following code can disable the bucket server-side encryption function
1$client->deleteBucketEncryption($bucket);
Bucket access log rules
To track access requests to BOS, users can enable the access log feature for the bucket. Each access log provides detailed information about a single request, including the requester, bucket name, request time, and operation performed. The logging function is useful for access statistics and security audits. Once the access log feature is enabled, the bucket automatically logs access requests into a user-specified bucket as log files, following a standardized naming convention on an hourly basis.
Enable bucket access logs
The following code enables bucket access logs and specifies the bucket for storing logs and the file prefix of access logs
1$logging = array(
2 'targetBucket' => $bucket.'logging',
3 'targetPrefix' => 'TargetPrefixName'
4);
5$client->putBucketLogging($bucket, $logging);
Get the access log configuration of the bucket
The following code gets the access log configuration of a bucket
1$response = $client->getBucketLogging($bucket);
Disable the access logging function of a bucket
1$client->deleteBucketLogging($bucket);
Bucket cross-region replication rules
Set cross-region replication rules
The following code sets cross-region replication rules for bj_bucket, and the destination bucket is gz_bucket
1$replication_rule = array(
2 'status' => 'enabled',
3 'replicateDeletes' => 'enabled',
4 'id' => 'sample'
5 );
6$replication_rule['resource'][0] = $bj_bucket . "/*";
7$replication_rule['destination']['bucket'] = $gz_bucket;
8$replication_rule['replicateHistory']['bucket'] = $gz_bucket;
9$bj_client->putBucketReplication($bj_bucket, $replication_rule);
Get cross-region replication rules
The following code is used to get information about the bucket for data synchronization, including the source bucket name, destination bucket name, storage class, whether to perform historical replication, data synchronization strategy, etc.
1$response = $bj_client->getBucketReplication($bj_bucket);
Get cross-region replication progress
The following code can be used to get the progress status of data synchronization replication
1$response = $bj_client->getBucketReplicationProgress($bj_bucket);
Delete cross-region replication rules
The following code can delete the data synchronization replication configuration
1$bj_client->deleteBucketReplication($bj_bucket);
Bucket static website hosting
BOS allows users to host static websites on their buckets, enabling streamlined website operation and maintenance. Once configured, users can access their hosted website by directly using the bucket's domain name.
Set bucket static website hosting rules
Users need FULL_CONTROL permissions for the bucket. It is not recommended to use archive files, as unretrieved archive files are unreadable, rendering the StaticWebsite feature ineffective in such cases.
1$static_website = array(
2 'index' => 'index.html',
3 'notFound' => '404.html'
4);
5$client->putBucketStaticWebsite($bucket, $static_website);
Get bucket static website hosting rules
1$response = $client->getBucketStaticWebsite($bucket);
Delete bucket static website hosting rules
1$client->deleteBucketStaticWebsite($bucket);
Bucket trash rules
To enhance the reliability of BOS data, BOS offers a bucket trash feature. Users with Full Control permissions who own the bucket can configure this bucket trash functionality.
Enable bucket trash function
To enable the bucket trash feature, the user must own the source bucket with FULL_CONTROL permissions and also own the target bucket.
1$client->putBucketTrash($bucket, '.trashDirName');
Remarks: If the trash function is enabled, it will overwrite the original directory name. Archive storage class files do not support bucket trash, and it will be deleted directly when the archive storage class files are deleted.
Get the activation status of bucket trash
Retrieve the status of the bucket trash feature and return the current trash directory name, defaulting to ".trash." The user must own the source bucket with FULL_CONTROL permissions and also own the target bucket.
1$response = $client->getBucketTrash($bucket);
Disable bucket trash function
To disable the trash feature, the user must own the source bucket with FULL_CONTROL permissions and also own the target bucket.
1$client->deleteBucketTrash($bucket);
Original image protection function of bucket
BOS supports an original image protection feature implemented through the API. Users can define the scope of the protection using the resource field. When this feature is enabled, anonymous access, downloads, or access with custom image processing parameters are prohibited. Only style-based access or access with valid signatures is permitted.
Enable the original image protection function of bucket
The following code activates the original image protection feature for a bucket and uses the resource field to specify its effective scope. For files under this protection, anonymous downloads, access, and access with custom image processing parameters are not allowed. Only style-based access or access with valid signatures is supported.
1$copyright_protection = array(
2 $bucket.'/prefix/*',
3 $bucket.'/*/suffix'
4);
5$client->putBucketCopyrightProtection($bucket, $copyright_protection);
Get the original image protection configuration of bucket
1$response = $client->getBucketCopyrightProtection($bucket);
Disable original image protection function of bucket
1$client->deleteBucketCopyrightProtection($bucket);
Set bucket storage class
Set bucket storage class
1// STANDARD represents standard storage, STANDARD_IA represents infrequent access storage, COLD represents cold storage, and ARCHIVE represents archive type;
2 // For multi-AZ type buckets, only MAZ_STANDARD and MAZ_STANDARD_IA storage classes are allowed to be set
3$storageClass = "STANDARD";
4$client->putBucketStorageClass($bucketName, $storageClass);
Get bucket storage class
1$client->getBucketStorageClass($bucketName)
