Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar metadados de objetos usando o OSS SDK for PHP 2.0

Última atualização: Sep 24, 2026

Este tópico descreve como configure e consultar metadados de objetos usando o OSS SDK for PHP.

Observações de uso

  • O código de exemplo neste tópico utiliza o ID de região cn-hangzhou da região China (Hangzhou). Por padrão, um endpoint público é usado para acessar recursos em um bucket. Para acessar os recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Para configure metadados de objetos, você precisa da permissão oss:PutObject. Para consultar metadados de objetos, você precisa da permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Configurar metadados durante o upload de objetos

Configurar metadados durante o upload de objetos

O código de exemplo a seguir envia um objeto usando PutObject e define cabeçalhos de metadados como o tempo de expiração, a access control list (ACL) e alguns metadados de usuário. Você pode configure metadados de objetos da mesma forma ao utilizar outras operações de API de upload.

<?php

// Include the autoload file so that the required dependencies can be loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and 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 for accessing 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.
    "file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // (Required) Specify the path of the local file.
];

// Convert the parameter descriptions into the long options format 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$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 the object.
$file = $options["file"];     // The path of the local file.

// Obtain access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve 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();
$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 one is provided.
}

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

// Check whether the file exists.
if (!file_exists($file)) {
    echo "Error: The specified file does not exist." . PHP_EOL; // If the file does not exist, print an error message and exit.
    exit(1);
}

// Open the local file and prepare for the upload.
// Open the local file in read-only mode and convert the file content into a stream by using Utils::streamFor.
$body = Oss\Utils::streamFor(fopen($file, 'r'));

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(
            bucket: $bucket,
            key: $key,
            metadata: [ 'Author' => 'alibaba oss sdk',
                        'Date' => '2024-07-01']); // Configure object metadata.

$request->body = $body; // Set the request body to the file stream.

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

// Display the result of the object upload operation.
// Display the HTTP status code, request ID, and ETag, 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 the request.
    'etag:' . $result->etag . PHP_EOL               // The ETag of the object, which is used to uniquely identify the object.
);

Consultar metadados de objetos

Consultar todos os metadados de um objeto usando o método HeadObject

O código de exemplo a seguir consulta todos os metadados de um objeto por meio do método HeadObject:

<?php

// Include the autoload file so that the required dependencies can be loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and 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 for accessing 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 into the long options format 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$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 the object.

// Obtain access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve 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();
$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 one is provided.
}

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

// Create a HeadObjectRequest object to obtain the metadata of the object.
$request = new Oss\Models\HeadObjectRequest($bucket, $key);

// Query object metadata.
$result = $client->headObject($request);

// Print the 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 the request.
    'result:' . var_export($result, true) . PHP_EOL  // The metadata returned.
);

Usar o método GetObjectMeta para consultar metadados parciais de um objeto

Nota

O método GetObjectMeta retorna apenas metadados parciais do objeto, incluindo o tamanho do conteúdo (ContentLength), a entity tag (ETag), o horário da última modificação (LastModified), o horário do último acesso (LastAccessTime), o ID de versão (VersionId) e o hash CRC-64 (HashCRC64).

O código de exemplo a seguir consulta metadados parciais de um objeto por meio do método GetObjectMeta:

<?php

// Include the autoload file so that the required dependencies can be loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and 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 for accessing 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 into the long options format 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$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 the object.

// Obtain access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve 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();
$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 one is provided.
}

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

// Create a GetObjectMetaRequest object to query the metadata of the object.
$request = new Oss\Models\GetObjectMetaRequest($bucket, $key);

// Query object metadata.
$result = $client->getObjectMeta($request);

// Print the 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 the request.
    'result:' . var_export($result, true) . PHP_EOL  // The metadata returned.
);

Modificar os metadados de um objeto existente

Usar o método **CopyObject** para modifique os metadados de um objeto

O código de exemplo a seguir modifique os metadados de um objeto por meio do método CopyObject:

<?php

// Include the autoload file so that the required dependencies can be loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and 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 for accessing 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.
    "src-key" => ['help' => 'The name of the source object', 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the parameter descriptions into the long options format 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$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.
// Use EnvironmentVariableCredentialsProvider to retrieve 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();
$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 one is provided.
}

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

// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key,
            metadata: [ 'x-oss-meta-tag1' => 'value1',
            'x-oss-meta-tag2' => 'value2'],
            metadataDirective: 'Replace');

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 the request.
);

Usar **Copier.Copy** para modifique os metadados de um objeto

O Copier.Copy permite copiar um objeto de source e defina os metadados do objeto de destino. Você pode, por exemplo, sobrescrever todos os metadados originais com novos valores, remover os metadados originais ou atualize apenas cabeçalhos específicos. Também é possível indicar se o objeto de source deve ser excluído após a conclusão da cópia.

<?php

// Include the autoload file so that the required dependencies can be loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and 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 for accessing 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 destination object.
    "src-key" => ['help' => 'The name of the source object', 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the parameter descriptions into the long options format 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$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 destination object.
$srcKey = $options["src-key"]; // The name of the source object.

// Obtain access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve 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();
$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 one is provided.
}

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

// Create a Copier instance.
$copier = $client->newCopier();

$dstKey = "multipart-copy-replace-metadata-and-tagging-$key"; // Specify the name of the destination object.
$copyRequest = new Oss\Models\CopyObjectRequest(
    bucket: $bucket,
    key: $dstKey,
    sourceBucket: $bucket,
    sourceKey: $srcKey
);
$copyRequest->metadataDirective = 'REPLACE'; // Replace object metadata.
$copyRequest->metadata = ['test1' => 'val1', 'test2' => 'value2']; // Specify the user metadata.
$result = $copier->copy(
    request: $copyRequest,
);
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
    'request id:' . $result->requestId . PHP_EOL     // The request ID.
);