All Products
Search
Document Center

Object Storage Service:Configure object tags (OSS SDK for PHP V2)

Last Updated:Mar 20, 2026

Object Storage Service (OSS) lets you attach tags to objects to classify and manage them. This topic shows how to configure object tags using OSS SDK for PHP 2.0.

Usage notes

  • The examples use the region ID cn-hangzhou (China (Hangzhou)) and a public endpoint. To access OSS from other Alibaba Cloud products in the same region, use an internal endpoint instead. For supported regions and endpoints, see Regions and endpoints.

  • Configuring object tags requires the oss:PutObjectTagging permission. For details, see Attach a custom policy to a RAM user.

Operations overview

ScenarioHow to pass tagsKey parameter or API
Simple uploadInline with the upload requesttagging on PutObjectRequest
Multipart uploadInline when initiating the uploadtagging on InitiateMultipartUploadRequest
Append uploadInline with the first append requesttagging on AppendObjectRequest
Copy objectReplace source tags during copytaggingDirective: "Replace" + tagging on CopyObjectRequest
Existing objectDedicated tagging API (replaces all tags)PutObjectTaggingRequest

Set tags during upload

All upload examples use the URL-encoded string format for tags: "key1=value1&key2=value2".

Simple upload

<?php

// Load dependencies.
require_once __DIR__ . '/../../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and parse command line parameters.
$optsdesc = [
    "region"   => ['help' => 'The region where the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The endpoint for OSS access.', 'required' => False],
    "bucket"   => ['help' => 'The bucket name.', 'required' => True],
    "key"      => ['help' => 'The object name.', 'required' => True],
];

$longopts = \array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);

// Upload the object with tags.
$request       = new Oss\Models\PutObjectRequest(
    bucket:  $bucket,
    key:     $key,
    tagging: "key1=value1&key2=value2"  // Specify tags as a URL-encoded string.
);
$request->body = Oss\Utils::streamFor('Hello OSS');

$result = $client->putObject($request);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL .
    'etag: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Multipart upload

Tags are set when you initiate the multipart upload.

<?php

// Load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and parse command line parameters.
$optsdesc = [
    "region"   => ['help' => 'The region where the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The endpoint for OSS access.', 'required' => False],
    "bucket"   => ['help' => 'The bucket name.', 'required' => True],
    "key"      => ['help' => 'The object name.', 'required' => True],
];

$longopts = \array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);

// Initiate the multipart upload and attach tags.
$initRequest = new Oss\Models\InitiateMultipartUploadRequest(
    bucket:  $bucket,
    key:     $key,
    tagging: "key1=value1&key2=value2"  // Tags apply to the final assembled object.
);
$initResult = $client->initiateMultipartUpload($initRequest);
$uploadId   = $initResult->uploadId;

// Upload parts from a local file (1 MB per part).
$bigFileName = "/Users/localpath/yourfilename";
$partSize    = 1 * 1024 * 1024;

$file  = fopen($bigFileName, 'r');
$parts = [];

if ($file) {
    $i = 1;
    while (!feof($file)) {
        $chunk      = fread($file, $partSize);
        $partResult = $client->uploadPart(
            new Oss\Models\UploadPartRequest(
                bucket:        $bucket,
                key:           $key,
                partNumber:    $i,
                uploadId:      $uploadId,
                contentLength: null,
                contentMd5:    null,
                trafficLimit:  null,
                requestPayer:  null,
                body:          Oss\Utils::streamFor(resource: $chunk)
            )
        );
        $parts[] = new Oss\Models\UploadPart(
            partNumber: $i,
            etag:       $partResult->etag,
        );
        $i++;
    }
    fclose($file);
}

// Complete the multipart upload.
$comResult = $client->completeMultipartUpload(
    new Oss\Models\CompleteMultipartUploadRequest(
        bucket:   $bucket,
        key:      $key,
        uploadId: $uploadId,
        acl:      null,
        completeMultipartUpload: new Oss\Models\CompleteMultipartUpload(
            parts: $parts
        ),
    )
);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL,
    $comResult->statusCode,
    $comResult->requestId
);
var_export($comResult);

Append upload

<?php

// Load dependencies.
require_once __DIR__ . '/../../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and parse command line parameters.
$optsdesc = [
    "region"   => ['help' => 'The region where the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The endpoint for OSS access.', 'required' => False],
    "bucket"   => ['help' => 'The bucket name.', 'required' => True],
    "key"      => ['help' => 'The object name.', 'required' => True],
];

$longopts = \array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);

// Append data to the object with tags.
$request          = new Oss\Models\AppendObjectRequest(
    bucket:  $bucket,
    key:     $key,
    tagging: "key1=value1&key2=value2"
);
$request->body     = Oss\Utils::streamFor('Hello Append Object');
$request->position = 0;  // Set to 0 for the first append.

$result = $client->appendObject($request);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL .
    'next append position: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId,
    $result->nextPosition
);

Copy object

Use taggingDirective: "Replace" to assign new tags to the destination object instead of copying the source object's tags.

<?php

// Load dependencies.
require_once __DIR__ . '/../../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and parse command line parameters.
$optsdesc = [
    "region"     => ['help' => 'The region where the bucket is located.', 'required' => True],
    "endpoint"   => ['help' => 'The endpoint for OSS access.', 'required' => False],
    "bucket"     => ['help' => 'The destination bucket name.', 'required' => True],
    "key"        => ['help' => 'The destination object name.', 'required' => True],
    "src-bucket" => ['help' => 'The source bucket name.', 'required' => False],
    "src-key"    => ['help' => 'The source object name.', 'required' => True],
];

$longopts = \array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];
$srcKey = $options["src-key"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);

// Copy the object and replace its tags.
$request = new Oss\Models\CopyObjectRequest(
    bucket:           $bucket,
    key:              $key,
    sourceKey:        $srcKey,
    taggingDirective: "Replace",             // Replace source tags with the new tag set below.
    tagging:          "key1=value1&key2=value2"
);

if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"];
}
$request->sourceKey = $srcKey;

$result = $client->copyObject($request);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);

Add or update tags on an existing object

If an existing object has no tags or the tags of the object do not meet your requirements, you can add tags to or modify the tags of the object.

<?php

// Load dependencies.
require_once __DIR__ . '/../../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and parse command line parameters.
$optsdesc = [
    "region"   => ['help' => 'The region where the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The endpoint for OSS access.', 'required' => False],
    "bucket"   => ['help' => 'The bucket name.', 'required' => True],
    "key"      => ['help' => 'The object name.', 'required' => True],
];

$longopts = \array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];

// Load credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}
$client = new Oss\Client($cfg);

// Replace all tags on the object with the specified tag set.
$request = new Oss\Models\PutObjectTaggingRequest(
    bucket:  $bucket,
    key:     $key,
    tagging: new Oss\Models\Tagging(
        tagSet: new Oss\Models\TagSet(
            tags: [
                new Oss\Models\Tag('k1', 'v1'),
                new Oss\Models\Tag('k2', 'v2'),
            ]
        )
    )
);

$result = $client->putObjectTagging($request);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);