En este tema se describe cómo configurar y consultar los metadatos de un objeto mediante OSS SDK for PHP.
Notas de uso
El código de ejemplo de este tema usa el identificador de región
cn-hangzhou, correspondiente a China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si necesita acceder a dichos recursos 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 los metadatos de un objeto, debe contar con el permiso
oss:PutObject. Para consultarlos, requiere el permisooss:GetObject. Para más detalles, consulte Grant a custom policy.
Configuración de metadatos durante la carga de objetos
Configure object metadata during object uploads
A continuación, el código de ejemplo carga un objeto mediante PutObject y configura encabezados de metadatos como el tiempo de expiración, la lista de control de acceso (ACL) y algunos metadatos de usuario. Puede aplicar el mismo procedimiento si utiliza otras operaciones de API de carga.
<?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.
);
Consulta de metadatos de objetos
Query all metadata of an object by using the HeadObject method
A continuación, el código de ejemplo consulta todos los metadatos de un objeto mediante el 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.
);
Use the GetObjectMeta method to query partial metadata of an object
Con el método GetObjectMeta solo es posible consultar una parte de los metadatos del objeto. Entre ellos se incluyen la longitud del contenido devuelto (ContentLength), la etiqueta de entidad (ETag), la hora de última modificación (LastModified), la hora de último acceso (LastAccessTime), el identificador de versión (VersionId) y el hash CRC-64 (HashCRC64).
A continuación, el código de ejemplo consulta parte de los metadatos de un objeto mediante el 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.
);
Modificación de metadatos de un objeto existente
Use the **CopyObject** method to modify object metadata
A continuación, el código de ejemplo modifica los metadatos de un objeto mediante el 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.
);
Use **Copier.Copy** to modify object metadata
La función Copier.Copy permite copiar un objeto de origen y configurar los metadatos del objeto de destino. Por ejemplo, puede sobrescribir todos los metadatos originales con valores nuevos, eliminar los metadatos existentes o actualizar únicamente los encabezados específicos. También es posible indicar si el objeto de origen se elimina al finalizar la copia.
<?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.
);