Todos os produtos
Search
Central de documentação

Object Storage Service:Cross-origin resource sharing (PHP SDK V1)

Última atualização: Sep 22, 2026

O compartilhamento de recursos entre origens (CORS) permite que aplicações web acessem recursos de origens diferentes. O Object Storage Service (OSS) disponibiliza operações de API para CORS, controlando as permissões de acesso entre origens.

Precauções

  • Neste tópico, utiliza-se o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints compatíveis, consulte Regions and endpoints.

  • Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Create an OssClient.

  • Para defina regras de CORS, você precisa da permissão oss:PutBucketCors. Para recuperar regras de CORS, é necessária a permissão oss:GetBucketCors. Para exclua regras de CORS, é necessária a permissão oss:DeleteBucketCors. Para mais informações, consulte Grant custom permissions to a RAM user.

Defina regras de CORS

O código a seguir demonstra como defina as regras de CORS para o bucket 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;

// Get access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Set bucket to the name of your bucket, for example, examplebucket.
$bucket= "examplebucket";

$corsConfig = new CorsConfig();
$rule = new CorsRule();
// Set the allowed response headers for cross-origin requests. You can set multiple AllowedHeader values. Each value can contain at most one asterisk (*) wildcard character.
// Set AllowedHeader to an asterisk (*) if you have no special requirements.
$rule->addAllowedHeader("*");
// Set the response headers that users can access from the application. You can set multiple ExposeHeader values. The asterisk (*) wildcard character is not supported in ExposeHeader.
$rule->addExposeHeader("x-oss-header");
// Set the allowed origins for cross-origin requests. You can set multiple AllowedOrigin values. Each value can contain at most one asterisk (*) wildcard character.
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// To allow requests from all origins, set AllowedOrigin to an asterisk (*).
//$rule->addAllowedOrigin("*");
// Set the allowed methods for cross-origin requests.
$rule->addAllowedMethod("POST");
// Set the cache duration for the response to a preflight (OPTIONS) request. The unit is seconds.
$rule->setMaxAgeSeconds(10);
// A maximum of 10 rules can be added to each bucket.
$corsConfig->addRule($rule);
// Specify whether to return the Vary: Origin header. If this is set to false, the Vary: Origin header is never returned.
$corsConfig->setResponseVary(false);

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    // Existing rules are overwritten.
    $ossClient->putBucketCors($bucket, $corsConfig);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            

Obter regras de CORS

O código a seguir mostra como recuperar as regras de CORS do bucket 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 {
    // Get access credentials from environment variables and save them in the provider. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    $provider = new EnvironmentVariableCredentialsProvider();
    // Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // Set bucket to the name of your bucket, for example, examplebucket.
    $bucket= "examplebucket";
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"        
    );
    $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;
}

Exclua regras de CORS

O código a seguir exemplifica como exclua todas as regras de CORS do bucket 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;

// Get access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Set bucket to the name of your bucket, for example, examplebucket.
$bucket= "examplebucket";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

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

Referências

  • Para acessar o código de exemplo completo de gerenciamento de regras de CORS, consulte GitHub.

  • Para mais informações sobre a operação de API que configure regras de CORS, consulte PutBucketCors.

  • Para detalhes sobre a operação de API que consulta regras de CORS, veja GetBucketCors.

  • Para saber mais sobre a operação de API que exclui regras de CORS, veja DeleteBucketCors.