Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie versionamento (OSS SDK for PHP V2)

Última atualização: Jul 03, 2026

A configuração de versionamento de um bucket aplica-se a todos os objetos nele contidos. Ao ativar o versionamento do bucket, é possível recuperar qualquer versão anterior de um objeto caso ele seja sobrescrito ou excluído acidentalmente.

Considerações

  • O código de exemplo deste tópico usa a região China (Hangzhou) (ID: cn-hangzhou) como referência. Por padrão, o código utiliza o endpoint público. Para acessar o OSS a partir de outros produtos da Alibaba Cloud na mesma região, use o endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o OSS, consulte Regiões e endpoints do OSS.

  • Para definir o estado de versionamento de um bucket, você precisa da permissão oss:PutBucketVersioning. Para consultar o estado de versionamento, é necessária a permissão oss:GetBucketVersioning. Para obter mais detalhes, consulte Conceder permissões personalizadas a um usuário RAM.

Código de exemplo

Defina o estado de versionamento de um bucket

Use o código a seguir para definir o estado de versionamento de um bucket como Enabled.

<?php

// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
];

// Convert the argument descriptions to the long option format required by getopt.
// Add a colon ":" after each argument to indicate that it requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Verify that the required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a PutBucketVersioningRequest object to enable the versioning feature for the bucket.
$request = new Oss\Models\PutBucketVersioningRequest(
    bucket: $bucket,
    versioningConfiguration: new Oss\Models\VersioningConfiguration(
        status: 'Enabled' // Set the versioning status to "Enabled".
    )
);

// Execute the operation to enable versioning for the bucket.
$result = $client->putBucketVersioning($request);

// Print the result of enabling versioning.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or trace the request.
);

Obter as informações do estado de versionamento de um bucket

Use o código a seguir para obter as informações do estado de versionamento de um bucket.

<?php

// Include the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the descriptions for command-line arguments.
$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],
];

// Convert the argument descriptions to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"];
$bucket = $options["bucket"];

// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default SDK configurations.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a GetBucketVersioningRequest object to retrieve the versioning status of the bucket.
$request = new Oss\Models\GetBucketVersioningRequest(
    bucket: $bucket
);

// Execute the operation to retrieve the versioning status of the bucket.
$result = $client->getBucketVersioning($request);

// Print the result of retrieving the versioning status.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
    'request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used for debugging or tracking requests.
    'version status:' . $result->versioningConfiguration->status . PHP_EOL // The versioning status, such as Enabled, Suspended, or an empty string.
);