Tous les produits
Search
Centre de documentation

Object Storage Service:Configurer le tagging d'objets à l'aide du SDK OSS pour PHP 2.0

Dernière mise à jour :Sep 25, 2026

Object Storage Service (OSS) vous permet de configurer des tags d'objet pour classer vos objets. Cette rubrique explique comment configurer des tags pour les objets à l'aide du SDK OSS pour PHP 2.0.

Notes d'utilisation

  • L'exemple de code présenté dans cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, un endpoint public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket via d'autres services Alibaba Cloud situés dans la même région que le bucket, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez la section Régions et endpoints.

  • Pour configurer des tags pour un objet, vous devez disposer de l'autorisation oss:PutObjectTagging. Pour plus d'informations, consultez la section Accorder une politique personnalisée.

Configurer des tags pour un objet lors de son téléchargement

Configurer des tags pour un objet lors de son téléchargement par upload simple

L'exemple de code suivant montre comment configurer des tags pour un objet lors de son téléchargement par upload simple :

<?php

// Introduce autoload files to load dependent libraries.
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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
$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 configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

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

// Specify the content that you want to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(
            bucket: $bucket,
            key: $key,
            tagging: "key1=value1&key2=value2"); // Specify the tag information.

$request-> body=Oss\Utils::streamFor($data); // Specify that the data in the HTTP request body is a binary stream.

// Perform the simple upload operation.
$result = $client->putObject($request);

// Display the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL . // The request ID.
    'etag: %s' . PHP_EOL, // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Configurer des tags pour un objet lors de son téléchargement par upload multipartie

L'exemple de code suivant montre comment configurer des tags pour un objet lors de son téléchargement par upload multipartie :

<?php

// Introduce autoload files to load dependent libraries.
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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

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

// Create a request to initiate the multipart upload task.
$request = new Oss\Models\InitiateMultipartUploadRequest(
                bucket: $bucket,
                key: $key,
                tagging:" key1=value1&key2=value2");

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

// Obtain the upload ID of the multipart upload task.
$uploadId = $result->uploadId;

// Create an UploadPartRequest object to upload the object.
$request = new Oss\Models\UploadPartRequest(bucket: $bucket, key: $key);

// Specify the path of the local file and the size of the parts.
$bigFileName = "/Users/localpath/yourfilename"; // Specify the path of the local file.
$partSize = 1 * 1024 * 1024; // Specify the size of the parts. Unit: bytes. In this example, this parameter is set to 1 MB.

// Open the local file and prepare for the multipart upload task.
$file = fopen($bigFileName, 'r');
$parts = []; // Store information about each part.
if ($file) {
    $i = 1; // Specify the part number starting from 1.
    while (!feof($file)) {
        $chunk = fread($file, $partSize); // Poll the part size.
        // Perform the multipart upload operation.
        $partResult = $client->uploadPart(
            new Oss\Models\UploadPartRequest(
                bucket: $bucket,
                key: $key,
                partNumber: $i, // Specify the number of the part.
                uploadId: $uploadId, // Specify the upload ID of the multipart upload task.
                contentLength: null,
                contentMd5: null,
                trafficLimit: null,
                requestPayer: null,
                body: Oss\Utils::streamFor(resource: $chunk) // Convert a data block to a stream.
            )
        );
        // Create an UploadPart object and record the part number and ETags.
        $part = new Oss\Models\UploadPart(
            partNumber: $i,
            etag: $partResult->etag,
        );
        array_push(array: $parts, values: $part); // Add the part information to the array.
        $i++; // Specify the part number. The part number sequentially increases.
    }
    fclose($file); // Close the file handles.
}

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

// Display the result of the multipart upload task.
printf(
    'status code:' . $comResult->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $comResult->requestId . PHP_EOL .   // The request ID, which is used to debug or trace a request.
    'complete multipart upload result:' . var_export($comResult, true) // The detailed result of the multipart upload task.
);

Configurer des tags pour un objet lors de son téléchargement par upload par ajout

L'exemple de code suivant montre comment configurer des tags pour un objet lors de son téléchargement par upload par ajout :

<?php

// Introduce autoload files to load dependent libraries.
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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

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

// Specify the content that you want to append.
$data='Hello Append Object'; // Replace the sample data with your actual content.

// Create an AppendObjectRequest object to append data to a specific object.
$request = new Oss\Models\AppendObjectRequest(
                bucket: $bucket,
                key: $key,
                tagging: "key1=value1&key2=value2");
$request-> body=Oss\Utils::streamFor($data); // Specify that the data in the HTTP request body is a binary stream.
$request->position = 0; // Set the position from which the first append operation starts to 0.

// Perform the append upload operation.
$result = $client->appendObject($request);

// Display the append upload result.
// Display the HTTP status code and the request ID to check whether the request is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL .    // The request ID, which is used to debug or trace a request.
    next append position:' . $result-> nextPosition. PHP_EOL // Specify the position from which the next append operation starts.
);

Configurer des tags pour un objet lors de sa copie

L'exemple de code suivant montre comment configurer des tags pour un objet lors de sa copie :

<?php

// Introduce autoload files to load dependent libraries.
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 destination bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the destination object.
    "src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // (Optional) Specify the name of the source bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the destination bucket.
$key = $options["key"]; // The name of destination object.
$srcKey = $options["src-key"]; // The name of the source object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

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

// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key,
            sourceKey: $srcKey,
            sourceBucket: $sourceBucket,
            taggingDirective: "Replace", // Replace the tags of the source object when you copy the source object.
            tagging:"key1=value1&key2=value2"); // Specify the tag information.

if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"]; // If the source bucket name is provided, specify the sourceBucket parameter.
}
$request->sourceKey = $srcKey; // Specify the name of the source object.

// Perform the object copy operation.
$result = $client->copyObject($request);

// Display the object copy result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);

Ajouter ou modifier des tags pour un objet existant

Ajouter ou modifier des tags pour un objet existant

Si un objet existant ne possède pas de tags ou si ses tags ne répondent pas à vos besoins, vous pouvez lui ajouter des tags ou modifier ses tags existants.

L'exemple de code suivant montre comment ajouter ou modifier des tags pour un objet existant :

<?php

// Introduce autoload files to load dependent libraries.
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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

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

// Create a PutObjectTaggingRequest object to configure tags for the object.
$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'), // Specify the tag key and value. Example: k1=v1.
                new Oss\Models\Tag('k2', 'v2') // Specify the tag key and value. Example: k2=v2.
            ]
        )
    )
);

// Configure the tags for the object.
$result = $client->putObjectTagging($request);

// Display the result of the request.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);