Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer les stratégies de bucket à l'aide du SDK OSS pour PHP 2.0

Dernière mise à jour :Aug 18, 2026

Une stratégie de bucket vous permet d'autoriser ou de restreindre l'accès d'utilisateurs anonymes ou identifiés, tels que les comptes Alibaba Cloud, les utilisateurs RAM et les rôles RAM, à des ressources Object Storage Service (OSS) spécifiques. Par exemple, vous pouvez accorder des autorisations en lecture seule sur des ressources OSS spécifiques à un utilisateur RAM d'un autre compte Alibaba Cloud.

Notes d'utilisation

  • Avant de configurer des stratégies de bucket, assurez-vous de bien connaître cette fonctionnalité. Pour plus d'informations, consultez la rubrique Stratégie de bucket.

  • L'exemple de code présenté dans cette rubrique utilise l'ID de région cn-hangzhou de 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 à l'aide d'autres services Alibaba Cloud situés dans la même région que le bucket, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez la rubrique Régions et endpoints.

  • Pour configurer une stratégie de bucket, vous devez disposer de l'autorisation oss:PutBucketPolicy. Pour interroger les stratégies de bucket, vous devez disposer de l'autorisation oss:GetBucketPolicy. Pour supprimer une stratégie de bucket, vous devez disposer de l'autorisation oss:DeleteBucketPolicy. Pour plus d'informations, consultez la rubrique Accorder une politique personnalisée.

Exemples

Configurer une stratégie de bucket

L'exemple de code suivant montre comment configurer une stratégie de bucket :

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify 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);

// Set the format of the bucket policy to JSON.
$policy = '{
    "Version":"1",
    "Statement":[
        {
            "Action":[
                "oss:PutObject",
                "oss:GetObject"
            ],
            "Effect":"Deny",
            "Principal":["1234567890"],
            "Resource":["acs:oss:*:1234567890:*/*"]
        }
    ]
}';

// Create a request to configure the bucket policy and pass the bucket policy.
$request = new Oss\Models\PutBucketPolicyRequest(bucket: $bucket, policy: $policy);

// Use the putBucketPolicy method to specify the bucket policy.
$result = $client->putBucketPolicy($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result-> requestId. PHP_EOL // The unique identifier of the request.
);

Interroger les stratégies de bucket

L'exemple de code suivant montre comment interroger les stratégies de bucket :

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify 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 request to query bucket policies.
$request = new Oss\Models\GetBucketPolicyRequest(bucket: $bucket);

// Use the getBucketPolicy method to query bucket policies.
$result = $client->getBucketPolicy($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request.
    'policy:' . $result->body // The content of the bucket policies.
);

Supprimer une stratégie de bucket

L'exemple de code suivant montre comment supprimer une stratégie de bucket :

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify 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 request to delete the bucket policy.
$request = new Oss\Models\DeleteBucketPolicyRequest(bucket: $bucket);

// Use the deleteBucketPolicy method to delete the bucket policy.
$result = $client->deleteBucketPolicy($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result-> requestId. PHP_EOL // The unique identifier of the request.
);

Références

  • Pour consulter l'exemple de code complet utilisé pour configurer une stratégie de bucket, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant de configurer une stratégie de bucket, consultez la rubrique PutBucketPolicy.

  • Pour consulter l'exemple de code complet utilisé pour interroger les stratégies de bucket, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant d'interroger les stratégies de bucket, consultez la rubrique GetBucketPolicy.

  • Pour consulter l'exemple de code complet utilisé pour supprimer une stratégie de bucket, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant de supprimer une stratégie de bucket, consultez la rubrique DeleteBucketPolicy.