Tous les produits
Search
Centre de documentation

Object Storage Service:Configuration des règles CORS avec le SDK OSS pour PHP 2.0

Dernière mise à jour :Aug 18, 2026

En raison de la politique de même origine des navigateurs, les requêtes inter-origines peuvent être rejetées lors de l'échange de données ou du partage de ressources entre différents noms de domaine. Cette rubrique explique comment configurer les règles de partage des ressources cross-origin (CORS). Vous pouvez y spécifier les noms de domaine autorisés à envoyer des requêtes, les méthodes HTTP utilisables pour les requêtes cross-origin ainsi que les en-têtes autorisés.

Remarques sur l'utilisation

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou correspondant à la région Chine (Hangzhou). Par défaut, un endpoint public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket via d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez la section Régions et endpoints.

  • Pour configurer les règles CORS, vous devez disposer de l'autorisation oss:PutBucketCors. Pour consulter les règles CORS, l'autorisation oss:GetBucketCors est requise. Enfin, pour supprimer les règles CORS, vous devez détenir l'autorisation oss:DeleteBucketCors. Pour en savoir plus, reportez-vous à la section Accorder une stratégie personnalisée.

Exemples

Configurer les règles CORS

L'exemple de code suivant montre comment configurer une règle CORS pour un 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 configure a CORS rule for the bucket and specify the allowed sources and request methods for CORS.
$request = new Oss\Models\PutBucketCorsRequest(bucket: $bucket, corsConfiguration: new Oss\Models\CORSConfiguration(
        array(
            new Oss\Models\CORSRule(
                allowedOrigins: ['*'], // Allow a cross-origin request from all sources.
                allowedMethods: ['PUT', 'GET'] // Specify the allowed request methods for CORS.
            )
        )
    )
);

// Use the putBucketCors method to configure CORS configurations 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 request ID of the request, which is the unique identifier of the request.
);

Consulter les règles CORS

Le code ci-dessous illustre la procédure de consultation des règles CORS associées à un 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 configurations of a bucket.
$request = new Oss\Models\GetBucketCorsRequest(bucket: $bucket);

// Use the getBucketCors method to query the CORS configurations 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 request ID of the request, which is the unique identifier of the request.
    'cors:' . var_export($result->corsConfiguration, true) // The CORS configurations of the bucket.
);

Supprimer les règles CORS

Voici un exemple montrant comment supprimer toutes les règles CORS d'un 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 the CORS configurations of the bucket.
$request = new Oss\Models\DeleteBucketCorsRequest(bucket: $bucket);

// Use the deleteBucketCors method to delete the CORS configurations 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 request ID of the request, which is the unique identifier of the request.
);

Références

  • Pour accéder au code source complet relatif aux opérations CORS, rendez-vous sur les pages PutBucketCors, GetBucketCors et DeleteBucketCors.

  • Pour obtenir davantage de détails sur l'opération API permettant de configurer les règles CORS, consultez la documentation relative à PutBucketCors.

  • La documentation de l'opération API utilisée pour interroger les règles CORS est disponible ici : GetBucketCors.

  • Pour plus d'informations sur l'opération API servant à supprimer les règles CORS, voir DeleteBucketCors.