Manage data lifecycle by using OSS SDK for PHP
This topic describes how to manage the lifecycle of Object Storage Service (OSS) data by using OSS SDK for PHP V2.
Background information
Not all data stored in OSS are frequently accessed. However, infrequently accessed data must be retained to comply with data regulations or archiving requirements. OSS allows you to configure lifecycle rules that automate the management of the lifecycle of your data. You can configure two types of lifecycle rules:
-
Lifecycle rule based on the last modified time. This type of lifecycle rule can be used to delete data that has not been modified for an extended period or to move it to a more cost-effective storage class for cold data.
-
Lifecycle rule based on the last access time. This type of lifecycle rule can be used to identify data access patterns and automatically move cold data to a cost-effective storage class. This approach enables the implementation of tiered storage for hot and cold data, ultimately reducing storage costs.
Notes
-
Before you configure a lifecycle rule based on the last modified time or last access time, make sure that you are familiar with the lifecycle management feature. For more information, see Lifecycle rules based on last modification time and Lifecycle rules based on last access time.
-
The sample code in this topic uses the region ID
cn-hangzhouof the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region in which the bucket is located, use the internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints. -
To configure lifecycle rules, you must have the
oss:PutBucketLifecyclepermission. To query lifecycle rules, you must have theoss:GetBucketLifecyclepermission. To clear lifecycle rules, you must have theoss:DeleteBucketLifecyclepermission. For more information, see Grant a custom policy.
Configure lifecycle rules
This section provides code samples that configure lifecycle rules for a bucket based on the last modified time or last access time. You can modify one or more of the lifecycle rules configured for a bucket.
Configure a lifecycle rule based on the last modified time to change the storage class of objects with the specified name prefix
The following sample code configures a lifecycle rule based on the last modified time of objects to change the storage class of objects with the specified name prefix:
<?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;
// Describe 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.
];
// 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 and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$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);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Define a lifecycle rule that moves objects whose names are prefixed with "log/" to IA 30 days after they were last modified.
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA' // Change to IA.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configure a lifecycle rule based on the last modified time to change the storage class of objects without the specified name prefix or tags
The following sample code configures a lifecycle rule that moves objects without the "log" name prefix or without the "key1:value1" tag to Infrequent Access (IA) 30 days after they are last modified and expires them 100 days after the last modified time:
<?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;
// Describe 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.
];
// 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 and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$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);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
$lifecycleRule = new Oss\Models\LifecycleRule(
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'Archive' // Change the storage class to Archive.
)
),
filter: new Oss\Models\LifecycleRuleFilter( // Specify filters.
not: new Oss\Models\LifecycleRuleNot( // Specify exclusion filters.
prefix: 'log', // Exclude objects whose names contain the "log" prefix.
tag: new Oss\Models\Tag( // Specify tag filters.
key: 'key1',
value: 'value1'
)
)
),
expiration: new Oss\Models\LifecycleRuleExpiration(
days: 100 // Set the object expiration time to 100 days.
)
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configure a lifecycle rule based on the last access time to change the storage class
The following sample code configures a lifecycle rule based on the last access time to change the storage class:
<?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;
// Describe 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.
];
// 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 and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$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);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
{}
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA', // Change to IA.
isAccessTime: 'true', // Trigger the change based on the last access time.
returnToStdWhenVisit: 'true' // Return to the Standard storage class after they are accessed.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Query lifecycle rules
The following code queries lifecycle rules configured for a bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe 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.
];
// 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 and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$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);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to query lifecycle rules.
$request = new Oss\Models\GetBucketLifecycleRequest(bucket: $bucket);
// Call the getBucketLifecycle method to query lifecycle rules.
$result = $client->getBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'lifecycle:' . var_export($result->lifecycleConfiguration, true) . PHP_EOL // The lifecycle rules.
);
Clear lifecycle rules
The following sample code clears the lifecycle rules of a bucket. To delete one or more lifecycle rules, follow the instructions in Delete lifecycle rules
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe 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 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 and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$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);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to delete lifecycle rules of a bucket.
$request = new Oss\Models\DeleteBucketLifecycleRequest(bucket: $bucket);
// Call the deleteBucketLifecycle method to delete lifecycle rules.
$result = $client->deleteBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
References
-
For more information about the API operation that configures a lifecycle rule, see PutBucketLifecycle.
-
For more information about the API operation that queries lifecycle rules, see GetBucketLifecycle.
-
For more information about the API operation that deletes lifecycle rules, see DeleteBucketLifecycle.