Browsers enforce the same-origin policy, which blocks requests to a different domain than the page origin. Cross-origin resource sharing (CORS) lets you define which external origins can access resources in your OSS bucket and which HTTP methods they can use.
This topic shows how to configure, query, and delete CORS rules using the OSS PHP SDK V2.
Prerequisites
Before you begin, make sure you have:
An OSS bucket
The required RAM permissions for the operations you want to perform: For more information, see Attach a custom policy to a RAM user.
Operation Required permission Configure CORS rules oss:PutBucketCorsQuery CORS rules oss:GetBucketCorsDelete CORS rules oss:DeleteBucketCors
Usage notes
The sample code uses the China (Hangzhou) region (
cn-hangzhou) as an example. A public endpoint is used by default. To access OSS from other Alibaba Cloud products in the same region, use an internal endpoint. For region-to-endpoint mappings, see OSS regions and endpoints.
Examples
Configure CORS rules
The following example configures a CORS rule for a bucket.
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are 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"; // Specify that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a PutBucketCorsRequest object to configure a CORS rule for the bucket.
$request = new Oss\Models\PutBucketCorsRequest(bucket: $bucket, corsConfiguration: new Oss\Models\CORSConfiguration(
array(
new Oss\Models\CORSRule(
allowedOrigins: ['*'], // Allow requests from all origins.
allowedMethods: ['PUT', 'GET'] // Specify the allowed HTTP methods.
)
)
)
);
// Use the putBucketCors method to configure CORS rules for the bucket.
$result = $client->putBucketCors($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId // The unique identifier of the request.
);Query CORS rules
The following example retrieves the current CORS configuration of a bucket.
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are 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"; // Specify that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a GetBucketCorsRequest object to query the CORS configuration of the bucket.
$request = new Oss\Models\GetBucketCorsRequest(bucket: $bucket);
// Use the getBucketCors method to query the CORS configuration of the bucket.
$result = $client->getBucketCors($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request.
'cors:' . var_export($result->corsConfiguration, true) // The CORS configuration of the bucket.
);Delete CORS rules
The following example deletes all CORS rules of a bucket.
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are 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"; // Specify that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a DeleteBucketCorsRequest object to delete all CORS rules of the bucket.
$request = new Oss\Models\DeleteBucketCorsRequest(bucket: $bucket);
// Use the deleteBucketCors method to delete all CORS rules of the bucket.
$result = $client->deleteBucketCors($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId // The unique identifier of the request.
);References
For the complete sample code, see PutBucketCors, GetBucketCors, and DeleteBucketCors.
For the underlying API operations, see PutBucketCors, GetBucketCors, and DeleteBucketCors.