All Products
Search
Document Center

Object Storage Service:Set object tags (PHP SDK V2)

Last Updated:Aug 05, 2025

You can use object tagging in OSS to classify objects in buckets. This topic describes how to use the OSS SDK for PHP V2 to set object tags in a versioning-enabled bucket.

Notes

  • The sample code in this topic uses the China (Hangzhou) region (cn-hangzhou) as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see OSS regions and endpoints.

  • To set object tags, you must have the oss:PutObjectTagging permission. For more information, see Grant custom permissions to a RAM user.

Sample code

Note
  • In a versioning-enabled bucket, you can add or change the object tags for a specific version of an object by specifying its version ID.

  • For more information about how to obtain version IDs, see List objects.

You can use the following code to add or change the object tags for a specific version of an object.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
    "key" => ['help' => 'The name of the object', 'required' => True], // The name of the object. This parameter is required.
];

// 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);

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

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

// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read 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();
$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 PutObjectTaggingRequest object to set the tag information of the object.
$request = new Oss\Models\PutObjectTaggingRequest(
    bucket: $bucket,
    key: $key,
    versionId:"yourVersionId", // Specify the actual version ID.
    tagging: new Oss\Models\Tagging(
        tagSet: new Oss\Models\TagSet(
            tags: [
                new Oss\Models\Tag('k1', 'v1'), // The key-value pair of the tag: k1=v1.
                new Oss\Models\Tag('k2', 'v2')  // The key-value pair of the tag: k2=v2.
            ]
        )
    )
);

// Execute the operation to set object tags.
$result = $client->putObjectTagging($request);

// Print the result of setting object tags.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used for debugging or tracking requests.
);