Tous les produits
Search
Centre de documentation

Object Storage Service:Partage de ressources entre origines (PHP SDK V1)

Dernière mise à jour :Sep 22, 2026

Le partage de ressources entre origines (CORS) permet aux applications web d'accéder à des ressources provenant de différentes origines. Object Storage Service (OSS) propose des opérations API pour le CORS afin de contrôler les autorisations d'accès entre origines.

Précautions

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour plus de détails sur les régions et points de terminaison pris en charge, consultez Régions et points de terminaison.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Créer un OssClient.

  • Pour définir les règles CORS, vous devez disposer de l'autorisation oss:PutBucketCors. Pour récupérer les règles CORS, vous devez disposer de l'autorisation oss:GetBucketCors. Pour supprimer les règles CORS, vous devez disposer de l'autorisation oss:DeleteBucketCors. Pour plus d'informations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.

Définir les règles CORS

L'exemple de code suivant montre comment définir les règles CORS pour le 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");            

Obtenir les règles CORS

L'exemple de code suivant montre comment récupérer les règles CORS du 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;
}

Supprimer les règles CORS

L'exemple de code suivant montre comment supprimer toutes les règles CORS du 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");            

Références

  • Pour l'exemple de code complet de gestion des règles CORS, consultez GitHub.

  • Pour plus d'informations sur l'opération API permettant de configurer les règles CORS, consultez PutBucketCors.

  • Pour plus d'informations sur l'opération API permettant d'interroger les règles CORS, consultez GetBucketCors.

  • Pour plus d'informations sur l'opération API permettant de supprimer les règles CORS, consultez DeleteBucketCors.