Below is a code example for listing buckets in all regions within the current Alibaba Cloud account:
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Import the autoload file to load dependency libraries
use AlibabaCloud\Oss\V2 as Oss;
// Specify command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region must be specified. Example: oss-cn-hangzhou.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional. The endpoint that other services can use to access OSS.
];
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse command line parameters
$options = getopt("", $longopts);
// Check whether all required parameters have been configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
exit(1);
}
}
// Retrieve the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
// Use environment variables to load the credential information (AccessKey ID and AccessKey secret).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load the credential information from environment variables.
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault(); // Load the default configurations.
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Set the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a paginator for the ListBuckets operation.
$paginator = new Oss\Paginator\ListBucketsPaginator($client); // Create a paginator to list buckets.
$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest()); // Retrieve the pagination iterator.
// Traverse the paginated results.
foreach ($iter as $page) { // Traverse the list of buckets on each page.
foreach ($page->buckets ?? [] as $bucket) { // Traverse each bucket on the current page.
print ("Bucket: $bucket->name, $bucket->location\n"); // Print the bucket name and location.
}
}