All Products
Search
Document Center

Object Storage Service:Lifecycle management (PHP SDK V2)

Last Updated:Aug 05, 2025

This topic describes how to use PHP SDK V2 to manage the lifecycle feature of buckets.

Background information

In OSS, not all uploaded data requires frequent access. However, due to data compliance or archiving requirements, some data still needs to be preserved in cold storage. Based on your business requirements, you can choose:

  1. Lifecycle rules based on Last Modified Time: When certain data has not been modified for a long time and no longer needs to be retained, you can use this rule to delete them in batches or convert them to cold storage types, thereby freeing up storage space.

  2. Lifecycle rules based on Last Access Time: If you want OSS to automatically monitor data access patterns to identify cold data and dynamically convert storage types, you can enable this rule. OSS will automatically identify data that has not been accessed for a long time and convert it to more economical cold storage, achieving hot and cold tiering and reducing storage costs.

Considerations

  • Before configuring lifecycle rules based on the last modified time or last access time, make sure you understand this feature. For more information, see Lifecycle rules based on the last modified time and Lifecycle rules based on the last access time.

  • The sample code in this topic uses the China (Hangzhou) region ID cn-hangzhou and its public endpoint as an example. If you access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about the regions and endpoints that OSS supports, see OSS regions and endpoints.

  • To configure lifecycle rules, you must have the oss:PutBucketLifecycle permission. To view lifecycle rules, you must have the oss:GetBucketLifecycle permission. To delete lifecycle rules, you must have the oss:DeleteBucketLifecycle permission. For more information, see Grant custom permissions to a RAM user.

Configure lifecycle rules

The following code provides examples of lifecycle rules that are configured based on the last modified time and last access time of data. After the configuration is complete, if you want to modify one or more lifecycle rules, see How do I modify one or more lifecycle rule configurations?.

Configure a lifecycle rule based on the last modified time to change the storage classes of objects

The following code provides an example on how to configure a lifecycle rule based on the last modified time to change the storage classes of objects in a bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// 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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required 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

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration 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);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    prefix: 'log/', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA' // The target storage class is IA
        )
    ),
    id: 'rule', // The ID of the rule
    status: 'Enabled' // The status of the rule is enabled
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($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
);

Configure a lifecycle rule based on the last modified time to convert the storage class of objects, excluding the objects whose names contain specific prefixes or that have specific tags

The following code provides an example on how to specify that objects in a bucket, except for objects whose names contain the log prefix, objects that have the key1=value1 tag, and objects that meet the specified size requirements, are converted to the IA storage class 30 days after they are last modified and expire after 100 days.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// 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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required 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

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration 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);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    id: 'rule', // The ID of the rule
    status: 'Enabled', // The status of the rule is enabled
    prefix: 'logs', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA', // The target storage class is IA
            isAccessTime: false // Set to false, based on the last modified time policy
        )
    ),
    filter: new Oss\Models\LifecycleRuleFilter( // Define filter conditions
        objectSizeGreaterThan: 500, // Set greater than 500 bytes
        objectSizeLessThan: 1000, // Set less than 1000 bytes
        not: new Oss\Models\LifecycleRuleNot( // Define exclusion conditions
            prefix: 'logs/log', // Exclude objects with the log prefix
            tag: new Oss\Models\Tag( // Define tag conditions
                key: 'key1',
                value: 'value1'
            )
        )
    ),
    expiration: new Oss\Models\LifecycleRuleExpiration(
        days: 100 // The expiration time is 100 days
    )
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($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
);

Configure a lifecycle rule based on the last access time to change the storage classes of objects

The following code provides an example on how to configure a lifecycle rule based on the last access time to change the storage classes of objects in a bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;

// 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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required 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

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration 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);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    prefix: 'log/', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA', // The target storage class is IA
            IsAccessTime: 'true', // Whether to trigger the conversion based on the access time
            ReturnToStdWhenVisit: 'false' // Keep as IA storage when accessed again
        )
    ),
    id: 'rule', // The ID of the rule
    status: 'Enabled' // The status of the rule is enabled
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($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
);

View lifecycle rules

The following code provides an example on how to view the information contained in lifecycle rules.

<?php

// Include the autoload file to load dependencies
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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required 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

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration 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 object to get the lifecycle of the bucket
$request = new Oss\Models\GetBucketLifecycleRequest(bucket: $bucket);

// Call the getBucketLifecycle method to get the lifecycle rules of the bucket
$result = $client->getBucketLifecycle($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
    'lifecycle:' . var_export($result->lifecycleConfiguration, true) . PHP_EOL // The content of the lifecycle rules
);

Delete lifecycle rules

The following code provides an example on how to delete lifecycle rules configured for examplebucket. If you want to delete one or more lifecycle rules, see How do I delete one or more lifecycle rules?.

<?php

// Include the autoload file to load dependencies
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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required 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

// Use environment variables to load the AccessKey ID and AccessKey secret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration 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 object to delete the lifecycle rules of the bucket
$request = new Oss\Models\DeleteBucketLifecycleRequest(bucket: $bucket);

// Call the deleteBucketLifecycle method to delete the lifecycle rules of the bucket
$result = $client->deleteBucketLifecycle($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
);

References

  • For more information about the API operation that you can call to configure lifecycle rules, see PutBucketLifecycle.

  • For more information about the API operation that you can call to view lifecycle rules, see GetBucketLifecycle.

  • For more information about the API operation that you can call to delete lifecycle rules, see DeleteBucketLifecycle.