Todos los productos
Search
Centro de documentos

Object Storage Service:Configurar etiquetas de objetos con OSS SDK for PHP 2.0

Última actualización: Sep 25, 2026

Object Storage Service (OSS) permite configurar etiquetas en los objetos para clasificarlos. En este tema se describe cómo configurar etiquetas para los objetos mediante OSS SDK for PHP 2.0.

Notas de uso

  • El código de ejemplo de este tema utiliza el identificador de región cn-hangzhou, correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si necesita acceder a los recursos del bucket desde otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Para configurar etiquetas en un objeto, debe contar con el permiso oss:PutObjectTagging. Para obtener más información, consulte Grant a custom policy.

Configurar etiquetas al cargar un objeto

Configure etiquetas al cargar un objeto mediante carga simple

A continuación se muestra un ejemplo de código para configurar etiquetas en un objeto durante una carga 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
);

Configure etiquetas al cargar un objeto mediante carga multiparte

A continuación se muestra un ejemplo de código para configurar etiquetas en un objeto durante una carga multiparte:

<?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.
);

Configure etiquetas al cargar un objeto mediante carga por anexión

A continuación se muestra un ejemplo de código para configurar etiquetas en un objeto durante una carga por anexión:

<?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.
);

Configure etiquetas al copiar un objeto

A continuación se muestra un ejemplo de código para configurar etiquetas en un objeto durante su copia:

<?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.
);

Agregar o modificar etiquetas de un objeto existente

Agregue o modifique las etiquetas de un objeto existente

Si un objeto existente no tiene etiquetas o estas no cumplen con sus requisitos, agregue nuevas etiquetas o modifique las actuales.

A continuación se muestra un ejemplo de código para agregar o modificar las etiquetas de un objeto existente:

<?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.
);