Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie ACLs de objetos com o OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

Defina e consulte as listas de controle de acesso (ACLs) de objetos com o OSS SDK for PHP.

Observações de uso

  • Os códigos de exemplo deste tópico usam a região cn-hangzhou e o endpoint público por padrão. Se você acessar o bucket a partir de outro serviço da Alibaba Cloud na mesma região, use um endpoint interno para obter melhor desempenho e segurança. Para mais informações sobre regiões e endpoints, consulte Regiões e endpoints.

  • Para definir a ACL de um objeto, é necessária a permissão oss:PutObjectAcl. Para consultar a ACL de um objeto, é necessária a permissão oss:GetObjectAcl. Para mais informações, consulte Conceder uma política personalizada.

Tipos de ACLs

A tabela a seguir descreve os tipos de ACL disponíveis para um objeto.

ACL

Descrição

Valor

Herdada do bucket

O objeto herda a ACL do bucket onde está armazenado.

oss.ObjectACLDefault

Privada

Somente o proprietário do objeto e usuários autorizados podem ler e gravar o objeto. Outros usuários não podem acessar o objeto.

oss.ObjectACLPrivate

Leitura pública

Somente o proprietário do objeto e usuários autorizados podem ler e gravar o objeto. Outros usuários podem apenas ler o objeto. Tenha cuidado ao definir a ACL do objeto com este valor.

ObjectACLPublicRead

Leitura e escrita públicas

Todos os usuários podem ler e gravar o objeto. Tenha cuidado ao definir a ACL do objeto com este valor.

oss.ObjectACLPublicReadWrite

A ACL do objeto tem precedência sobre a ACL do bucket. Por exemplo, se um objeto em um bucket privado tiver a ACL de leitura pública, todos os usuários, inclusive anônimos, poderão ler o objeto. Se nenhuma ACL for definida para um objeto, ele herdará a ACL do bucket.

Código de exemplo

  1. Defina a ACL de um objeto.

    <?php
    
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    $optsdesc = [
        "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
        "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
        "bucket" => ['help' => 'The name of the bucket', 'required' => True],
        "key" => ['help' => 'The name of the object', 'required' => True],
    ];
    
    // Create an array of long options required by getopt. Example: --region:.
    $longopts = array_map(function ($key) {
        return "$key:";
    }, array_keys($optsdesc));
    
    // Parse the command line parameters.
    $options = getopt("", $longopts); 
    
    // Check whether the required parameters are missing.
    foreach ($optsdesc as $key => $value) {
        if ($value['required'] === True && empty($options[$key])) {
            // Print the help information and exit if required parameters are missing.
            $help = $value['help'];
            echo "Error: the following arguments are required: --$key, $help\n";
            exit(1);
        }
    }
    
    // Extract the values of the parameters.
    $region = $options["region"];
    $bucket = $options["bucket"];
    $key = $options["key"];
    
    // Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Load the default configurations and specify the credential provider and region.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider);
    $cfg->setRegion($region);
    
    // If the endpoint parameter is specified, it will be configured as the custom access URL.
    if (isset($options["endpoint"])) {
        $cfg->setEndpoint($options["endpoint"]);
    }
    
    // Initialize the OSSClient instance.
    $client = new Oss\Client($cfg);
    
    // Create a PutObjectAclRequest object and specify the bucket name, object key and ACL.
    $request = new Oss\Models\PutObjectAclRequest($bucket, $key, Oss\Models\ObjectACLType::PUBLIC_READ);
    
    // Set the ACL of the object to public-read.
    $result = $client->putObjectAcl($request);
    
    // Output the HTTP status code and request ID from the response.
    printf(
        'status code:' . $result->statusCode . PHP_EOL .
        'request id:' . $result->requestId
    );
    
  1. Consulte a ACL de um objeto.

    <?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 OSS endpoint.
        "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
        "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
    ];
    
    // 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 missing.
    foreach ($optsdesc as $key => $value) {
        if ($value['required'] === True && empty($options[$key])) {
            $help = $value['help'];
            echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
            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.
    $key = $options["key"]; // The name of the object.
    
    // Load the AccessKey ID and AccessKey secret from environment variables.
    $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);
    
    // If an endpoint is provided, specify the endpoint.
    if (isset($options["endpoint"])) {
        $cfg->setEndpoint($options["endpoint"]);
    }
    
    // Create an OSSClient instance.
    $client = new Oss\Client($cfg);
    
    // Create a request object for obtaining the ACL of the object.
    $request = new Oss\Models\GetObjectAclRequest(bucket: $bucket, key: $key);
    
    // Use the getObjectAcl method to query the ACL of the object.
    $result = $client->getObjectAcl($request);
    
    // Display the result.
    printf(
        'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
        'request id:' . $result->requestId . PHP_EOL . // The request ID.
        'acl:' . $result->accessControlList->grant // The ACL of the object.
    );
    

Referências

  • Para obter o código de exemplo completo sobre como definir a ACL de um objeto, visite o GitHub.

  • Para consultar a operação de API usada para definir a ACL de um objeto, veja PutObjectACL.

  • Para obter o código de exemplo completo sobre como consultar a ACL de um objeto, visite o GitHub.

  • Para consultar a operação de API usada para obter a ACL de um objeto, veja GetObjectACL.