All Products
Search
Document Center

Object Storage Service:CORS in PHP

Last Updated:Mar 11, 2024

Cross-origin resource sharing (CORS) allows web applications to access resources that belong to different origins. Object Storage Service (OSS) provides CORS API operations for cross-origin access control.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To configure CORS rules, you must have the oss:PutBucketCors permission. To query CORS rules, you must have the oss:GetBucketCors permission. To delete CORS rules, you must have the oss:DeleteBucketCors permission. For more information, see Attach a custom policy to a RAM user.

Configure CORS rules

The following code provides an example on how to configure CORS rules for a bucket named examplebucket:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;

// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

$corsConfig = new CorsConfig();
$rule = new CorsRule();
// Specify the response headers based on which cross-origin requests are allowed. You can specify multiple allowed headers. Only one asterisk (*) can be used as the wildcard character for each allowed header. 
// If you do not have special requirements, we recommend that you set AllowedHeader to an asterisk (*). 
$rule->addAllowedHeader("*");
// Specify the response headers that you are allowed to access from applications. You can specify multiple exposed headers. Exposed headers cannot contain asterisks (*). 
$rule->addExposeHeader("x-oss-header");
// Specify the allowed origins from which cross-origin requests are sent. You can specify multiple allowed origins. Only one asterisk (*) can be used as the wildcard character for each allowed origin. 
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// If you set AllowedOrigin to an asterisk (*), requests from all origins are allowed. 
//$rule->addAllowedOrigin("*");
// Specify the HTTP methods that cross-origin requests are allowed to use. 
$rule->addAllowedMethod("POST");
// Specify the time that the browser can cache the response to a preflight (OPTIONS) request to a specific resource. Unit: seconds. 
$rule->setMaxAgeSeconds(10);
// You can add up to 10 rules for each bucket. 
$corsConfig->addRule($rule);
// Specify whether to return the Vary: Origin header. A value of false indicates that the Vary: Origin header is not returned in any case.
$corsConfig->setResponseVary(false);

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

    // OSS overwrites an existing CORS rule that has the same name as the CORS rule that you want to create in the request. 
    $ossClient->putBucketCors($bucket, $corsConfig);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            

Query CORS rules

The following code provides an example on how to query the CORS rules configured for a bucket named examplebucket:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

try {
    // Obtain access credentials from environment variables and save the credentials in the provider. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    $provider = new EnvironmentVariableCredentialsProvider();
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Specify the name of the bucket. Example: examplebucket. 
    $bucket= "examplebucket";
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
    );
    $ossClient = new OssClient($config);
    $corsConfig = $ossClient->getBucketCors($bucket);

    if ($corsConfig->getResponseVary()){
        printf("Response Vary : true" .PHP_EOL);
    }else{
        printf("Response Vary : false" .PHP_EOL);
    }

    foreach ($corsConfig->getRules() as $key => $rule){
        if($rule->getAllowedHeaders()){
            foreach($rule->getAllowedHeaders() as $header){
                printf("Allowed Headers :" .$header .PHP_EOL);
            }
        }
        if ($rule->getAllowedMethods()){
            foreach($rule->getAllowedMethods() as $method){
                printf("Allowed Methods :" .$method . PHP_EOL);
            }

        }
        if($rule->getAllowedOrigins()){
            foreach($rule->getAllowedOrigins() as $origin){
                printf("Allowed Origins :" .$origin , PHP_EOL);
            }

        }
        if($rule->getExposeHeaders()){
            foreach($rule->getExposeHeaders() as $exposeHeader){
                printf("Expose Headers :" .$exposeHeader . PHP_EOL);
            }
        }
        printf("Max Age Seconds :" .$rule->getMaxAgeSeconds() .PHP_EOL);

    }
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}

Delete CORS rules

The following code provides an example on how to delete all CORS rules configured for a bucket named examplebucket:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name. Example: examplebucket. 
$bucket= "examplebucket";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

    $ossClient->deleteBucketCors($bucket);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            

References

  • For the complete sample code of CORS, visit GitHub.

  • For more information about the API operation that you can call to configure CORS rules, see PutBucketCors.

  • For more information about the API operation that you can call to query CORS rules, see GetBucketCors.

  • For more information about the API operation that you can call to delete CORS rules, see DeleteBucketCors.