Call GetBucketLocation to retrieve the region where a bucket resides.
Prerequisites
Before you begin, ensure that you have:
The
oss:GetBucketLocationpermission on the target bucket. For details, see Attach a custom policy to a RAM user
Usage notes
The sample code uses region ID
cn-hangzhou(China (Hangzhou)) as an example. By default, a public endpoint is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For supported regions and endpoints, see Regions and endpoints.
Get a bucket's region
The getBucketLocation method returns a location field containing the region ID of the bucket, for example, oss-cn-hangzhou.
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => true],
"endpoint" => ['help' => 'The domain name used to access OSS.', 'required' => false],
"bucket" => ['help' => 'The name of the bucket.', 'required' => true],
];
$longopts = array_map(fn($key) => "$key:", array_keys($optsdesc));
$options = getopt("", $longopts);
foreach ($optsdesc as $key => $value) {
if ($value['required'] === true && empty($options[$key])) {
echo "Error: the following arguments are required: --$key, " . $value['help'];
exit(1);
}
}
$region = $options["region"];
$bucket = $options["bucket"];
// Use environment variables to load credential information (AccessKeyId and AccessKeySecret).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);
// Call GetBucketLocation.
$request = new Oss\Models\GetBucketLocationRequest($bucket);
$result = $client->getBucketLocation($request);
printf(
"status code: %s\n" .
"request ID: %s\n" .
"location: %s\n",
$result->statusCode,
$result->requestId,
var_export($result->location, true)
);Run the script from the command line:
php get_bucket_location.php \
--region cn-hangzhou \
--bucket <your-bucket-name>The output looks similar to the following:
status code: 200
request ID: <request-id>
location: 'oss-cn-hangzhou'