Todos los productos
Search
Centro de documentos

Object Storage Service:Políticas de retención (SDK de PHP V2)

Última actualización: Sep 24, 2026

Object Storage Service (OSS) le permite establecer políticas de retención basadas en tiempo para los buckets. El periodo de retención puede abarcar desde 1 día hasta 70 años. En este tema se describe cómo crear, obtener, bloquear y cancelar una política de retención.

Notas de uso

  • El código de ejemplo de este tema usa de forma predeterminada el identificador de la región China (Hangzhou) cn-hangzhou y un endpoint público. Para acceder a OSS desde otros productos de Alibaba Cloud en la misma región, use un endpoint interno. Para más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema incluye un ejemplo sobre cómo leer las credenciales de acceso desde variables de entorno. Para más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

Código de ejemplo

Crear una política de retención

Use el siguiente código para crear una política de retención:

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));

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

// Check if any required arguments 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"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the software development kit (SDK).
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to initialize the retention policy for the bucket. Set the retention period to 3 days.
$request = new Oss\Models\InitiateBucketWormRequest(
    bucket: $bucket, 
    initiateWormConfiguration: new Oss\Models\InitiateWormConfiguration(
        retentionPeriodInDays: 3 // The retention period in days.
));

// Call the initiateBucketWorm method to initialize the retention policy for the bucket.
$result = $client->initiateBucketWorm($request);

// Print the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique ID of the request.
    'worm id:' . $result->wormId // The ID of the retention policy.
);

Cancelar una política de retención desbloqueada

Use el siguiente código para cancelar una política de retención desbloqueada:

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));

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

// Check if any required arguments 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"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to cancel the retention policy of the bucket.
$request = new Oss\Models\AbortBucketWormRequest(bucket: $bucket);

// Call the abortBucketWorm method to cancel the retention policy of the bucket.
$result = $client->abortBucketWorm($request);

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

Obtener una política de retención

Use el siguiente código para obtener la configuración de una política de retención:

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));

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

// Check if any required arguments 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"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$wormId = $options["worm-id"]; // The ID of the retention policy.

// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to get the retention policy of the bucket.
$request = new Oss\Models\GetBucketWormRequest(bucket: $bucket);

// Call the getBucketWorm method to get the retention policy of the bucket.
$result = $client->getBucketWorm($request);

// Print the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique ID of the request.
    'worm config:' . var_export($result->wormConfiguration, true) // The content of the retention policy configuration.
);

Ampliar el periodo de retención de un objeto

El siguiente código amplía el periodo de retención de una política de retención bloqueada:

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));

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

// Check if any required arguments 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"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$wormId = $options["worm-id"]; // The ID of the retention policy.

// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to extend the retention policy of the bucket. The extension period is 3 days.
$request = new Oss\Models\ExtendBucketWormRequest(
    bucket: $bucket, 
    wormId: $wormId,
    extendWormConfiguration: new Oss\Models\ExtendWormConfiguration(
        retentionPeriodInDays: 3 // The extension period is 3 days.
));

// Call the extendBucketWorm method to extend the retention policy of the bucket.
$result = $client->extendBucketWorm($request);

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

Documentos relacionados

  • Para más información sobre cómo crear una política de retención, consulte InitiateBucketWorm.

  • Para más información sobre cómo cancelar una política de retención desbloqueada, consulte AbortBucketWorm.

  • Para más información sobre cómo obtener la configuración de una política de retención, consulte GetBucketWorm.

  • Para más información sobre cómo ampliar el periodo de retención de una política de retención, consulte ExtendBucketWorm.