Initialization
Confirm Endpoint
Before configuring the Endpoint for SDK usage, please refer to the developer guide section on [BOS Access Domain Name](BOS/Developer Guide/Basic concepts.md#Endpoint) to understand Endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md). Refer to the following link for region and endpoint https://cloud.baidu.com/doc/BOS/s/akrqd2wcx 。 Currently, the corresponding information between BOS supported regions and access domain names is as follows:
| Access region | Endpoint |
|---|---|
| North China-Beijing | bj.bcebos.com |
| North China-Baoding | bd.bcebos.com |
| East China-Suzhou | su.bcebos.com |
| South China-Guangzhou | gz.bcebos.com |
| Southwest-Chengdu | cd.bcebos.com |
| Hong Kong | hkg.bcebos.com |
| Central China-Wuhan | fwh.bcebos.com |
| East China Finance-Shanghai | fsh.bcebos.com |
Retrieve access key
To use Baidu AI Cloud BOS, you need a valid AK (Access Key ID) and SK (Secret Access Key) for signature certification. AK/SK are system-assigned strings used to identify users and perform signature certification for BOS. Your AK/SK information can be obtained and understood through the following steps:
Create a BosClient
BosClient functions as a client for BOS services, giving developers various methods to interact with these services.
Before creating BosClient, a configuration file must be created to configure BosClient. Below, this configuration file is named YourConf.php, with the following specific configuration information:
1//Report all PHP errors
2error_reporting(-1);
3define('__BOS_CLIENT_ROOT', dirname(__DIR__));
4 //Set BosClient Access Key ID, Secret Access Key and ENDPOINT
5$BOS_TEST_CONFIG =
6 array(
7 'credentials' => array(
8 'accessKeyId' => 'your ak',
9 'secretAccessKey' => 'your sk',
10 'sessionToken' => 'your session token'
11 ),
12 'endpoint' => 'http://bj.bcebos.com',
13 'stsEndpoint' => 'http://sts.bj.baidubce.com',
14 );
15 //Set the log format and level
16$__handler = new \Monolog\Handler\StreamHandler(STDERR, \Monolog\Logger::DEBUG);
17$__handler->setFormatter(
18 new \Monolog\Formatter\LineFormatter(null, null, false, true)
19);
20\BaiduBce\Log\LogFactory::setInstance(
21 new \BaiduBce\Log\MonoLogFactory(array($__handler))
22);
23\BaiduBce\Log\LogFactory::setLogLevel(\Psr\Log\LogLevel::DEBUG);
Note:
- In the code above,
accessKeyIdcorresponds to “Access Key ID” in the console.secretAccessKeycorresponds to “Access Key Secret” in the console. For the method to retrieve them, refer to the Guide - [Manage ACCESSKEY](Reference/Retrieve AK and SK/How to Obtain AKSK.md).- If users need to specify their own domain name, they can upload the
ENDPOINTparameters, which must be defined with the domain name of the specified region. For example, if the service is located in Beijing, the endpoint will behttp://bj.bcebos.com.- If STS authentication is not used,
stsEndpoint和sessionTokencan be left empty or deleted.
Create a BosClient with AK/SK
Users can refer to the following code to create a BosClient to access BOS with AK/SK:
1//Use PHP SDK with a custom configuration file
2include 'BaiduBce.phar';
3require 'YourConf.php';
4use BaiduBce\BceClientConfigOptions;
5use BaiduBce\Util\MimeTypes;
6use BaiduBce\Http\HttpHeaders;
7use BaiduBce\Services\Bos\BosClient;
8 //Call parameters from configuration file
9global $BOS_TEST_CONFIG;
10 //Create a new BosClient
11$client = new BosClient($BOS_TEST_CONFIG);
Create a BosClient with STS
Request STS Token
BOS allows temporary third-party access authorization using the STS mechanism. STS (Security Token Service) is a temporary authorization tool provided by Baidu AI Cloud, enabling you to issue access credentials with customized validity periods and permissions for third-party users. These users can use the credentials to call Baidu AI Cloud APIs or SDKs directly to access cloud resources.
To access BOS via STS, users must first request a certification string through the STS client. For instructions on obtaining STS credentials, refer to [Baidu AI Cloud STS Usage Guide](BOS/API Reference/Access control.md).
Create BOSClient with STS token
After requesting the STS token, configure it in the BosClient. The following codes demonstrate how to create a BosClient:
-
First, configure the STS endpoint. Below is an example of STS configuration:
PHP1$BOS_TEST_CONFIG = 2 array( 3 'credentials' => array( 4 'accessKeyId' => 'your ak', 5 'secretAccessKey' => 'your sk', 6 ), 7 'stsEndpoint' => 'http://sts.bj.baidubce.com', 8 ); -
The sample code of StsClient is as follows:
PHP1use BaiduBce\Services\Sts\StsClient; 2 //Create StsClient 3$client = new StsClient($BOS_TEST_CONFIG); 4$aclArray = 5 array( 6 'id' => 'test-acl', 7 'accessControlList' => array( 8 array( 9 'permission' => array('GET'), 10 'service' => 'bce:bos', 11 'region' => 'bj', 12 'effect' => 'Allow', 13 'resource' => array('testbucket/*') 14 ) 15 ) 16 ); 17$request = 18 array( 19 'acl' => json_encode($aclArray), //User-defined acl 20 'durationSeconds' => 43200, //STS credential validity period 21 ); 22$response = $client->getSessionToken($request); 23$accessKeyID= $response->accessKeyId; 24$secretAccessKey= $response->secretAccessKey; 25$sessionToken = $response->sessionToken;Plain Text1> **Note:** The acl here refers to the user-defined access control list, and its syntax can be referred to in [Access Control](BOS/API Reference/Access control.md). -
Enter the retrived accessKeyID/secretAccessKey/sessionToken in the configuration file
YourConf.php, and create BosClient.PHP1$BOS_TEST_CONFIG = 2 array( 3 'credentials' => array( 4 'accessKeyId' => 'your ak', 5 'secretAccessKey' => 'your sk', 6 'sessionToken' => 'your session token' 7 ), 8 'endpoint' => 'http://bj.bcebos.com', 9 ); 10 //Create a new BosClient 11$client = new BosClient($BOS_TEST_CONFIG);
Note: Currently, when configuring a client with STS, regardless of where the corresponding BOS service endpoint is located, the endpoint must be set to
http://sts.bj.baidubce.com.
Configure HTTPS access to BOS
BOS supports HTTPS transport protocol. You can use HTTPS to access the BOS service in the BOS PHP SDK in the following two ways:
-
Specify HTTPS in the endpoint:
PHP1$BOS_CONFIG = 2 array( 3 'credentials' => array( 4 'ak' => 'your-ak', 5 'sk' => 'your-sk', 6 ), 7 'endpoint' => 'https://bj.bcebos.com', 8 ); 9$client = new BosClient($BOS_CONFIG); -
Set the HTTPS protocol by specifying
httpsinprotocol:PHP1$BOS_CONFIG = 2 array( 3 'credentials' => array( 4 'ak' => 'your-ak', 5 'sk' => 'your-sk', 6 ), 7 'endpoint' => 'bj.bcebos.com', 8 'protocol' => 'https', 9 ); 10$client = new BosClient($BOS_CONFIG);Plain Text1> **Note:** When you specify the protocol parameter along with the endpoint's scheme, the endpoint scheme takes precedence.PHP1$BOS_CONFIG = 2 array( 3 'credentials' => array( 4 'ak' => 'your-ak', 5 'sk' => 'your-sk', 6 ), 7 'endpoint' => 'http://bj.bcebos.com', 8 'protocol' => 'https', 9 ); 10 $client=newBosClient($BOS_CONFIG); //Will access BOS via HTTP
Access BOS using a custom domain name (CNAME)
You can access the BOS service using a custom domain name in the BOS PHP SDK in the following way:
Specify the custom domain name in the endpoint and set the custom field to true to indicate the use of a custom domain name:
1$BOS_CONFIG =
2 array(
3 'credentials' => array(
4 'ak' => 'your-ak',
5 'sk' => 'your-sk',
6 ),
7 'endpoint' => 'http://custom-domain.com',
8 'custom' => true,
9 );
10$client = new BosClient($BOS_CONFIG);
11$client->putObjectFromFile(null, $objectKey, $fileName);
Note: If you're using a custom domain name to create a BosClient in the PHP SDK, it is advised to set the bucketName field to null when accessing APIs. Currently, the PHP SDK does not support the copyObject and uploadPartCopy APIs when a custom domain name is used.
Configure BosClient
Set custom parameters
PHP SDK sets some default parameters in \BaiduBce\Bce.php. To modify these values, users may create custom parameter configuration functions with reference to this file, and pass them during BosClient construction. Reference code is as follows:
1public function CustomizedConfig() {
2 $customizedConfig = array(
3 BceClientConfigOptions::PROTOCOL => 'http',
4 BceClientConfigOptions::REGION => 'bj',
5 BceClientConfigOptions::CONNECTION_TIMEOUT_IN_MILLIS => 120 * 1000,
6 BceClientConfigOptions::SOCKET_TIMEOUT_IN_MILLIS => 300 * 1000,
7 BceClientConfigOptions::SEND_BUF_SIZE => 5 * 1024 * 1024,
8 BceClientConfigOptions::RECV_BUF_SIZE => 5 * 1024 * 1024,
9 BceClientConfigOptions::CREDENTIALS => array(
10 'ak' => 'your-access-key-id',
11 'sk' => 'your-secret-access-key',
12 ),
13 'endpoint' => 'your-endpoint',
14 );
15 //Create BOSClient with custom configuration
16 $customizedClient = new BosClient($customizedConfig);
17 //Call methods via custom configuration
18 $options = array(BosOptions::CONFIG=>$customizedConfig);
19 $this->client->listBuckets($options);
20}
The parameter description is as follows:
| Parameters | Description | Default value |
|---|---|---|
| PROTOCOL | Protocol | http |
| REGION | Region | bj |
| CONNECTION_TIMEOUT_IN_MILLIS | Request timeout duration (unit: millisecond) | 50 * 1000 |
| SOCKET_TIMEOUT_IN_MILLIS | Timeout for socket data transmission (unit: ms) | 0 (infinite waiting. if a non-zero value is set, file size and network speed shall be evaluated; otherwise, uploading large files may cause timeout.) |
| SEND_BUF_SIZE | Send buffer size | 1024 * 1024 |
| RECV_BUF_SIZE | Receive buffer size | 10 1024 1024 |
Set optional parameters
BosClient encapsulates optional parameters into $options. The optional parameters for each method can be found in the specific introduction of the API usage. Taking the putObjectFromFile method as an example, refer to the following code to set optional parameters:
1//Use options to pass specified parameters when uploading an object via a file
2file_put_contents($fileName, "test of put object from string");
3$user_meta = array("x-bce-meta-key1" => "value1");
4$options = array(
5 BosOptions::CONTENT_TYPE=>"text/plain",
6 BosOptions::CONTENT_MD5=>base64_encode(hash_file("md5", $fileName, true)),
7 BosOptions::CONTENT_LENGTH=>filesize($fileName),
8 BosOptions::CONTENT_SHA256=>hash_file("sha256", $fileName),
9 BosOptions::USER_METADATA => $user_meta,
10);
11$client->putObjectFromFile($bucketName, $objectKey, $fileName, $options);
Note: Do not pass
nullinto$options, otherwise an exception will be thrown during the call.
