This topic describes how to configure and query object metadata by using OSS SDK for PHP.
Usage notes
The sample code in this topic uses the region ID
cn-hangzhou
of the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.To configure object metadata, you must have the
oss:PutObject
permission. To query object metadata, you must have theoss:GetObject
permission. For more information, see Attach a custom policy to a RAM user.
Configure object metadata during object uploads
Configure object metadata during object uploads
The following sample code uploads an object by using PutObject and configures object metadata headers such as the expiration time, access control list (ACL), and some user metadata. You can configure object metadata in the same way if you use other upload API operations.
<?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.
);
Query object metadata
Query all metadata of an object by using the HeadObject method
The following sample code queries all metadata of an object by using the HeadObject method:
<?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
You can use the GetObjectMeta method to query only partial object metadata, including the returned content length (ContentLength), entity tag (ETag), last modified time (LastModified), last access time (LastAccessTime), version ID (VersionId), and CRC-64 hash (HashCRC64).
The following sample code queries partial metadata of an object by using the GetObjectMeta method:
<?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.
);
Modify metadata of an existing object
Use the CopyObject method to modify object metadata
The following sample code modifies the metadata of an object by using the CopyObject method:
<?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
You can use Copier.Copy to copy a source object and configure metadata for the destination object. For example, you can overwrite all existing original metadata with new metadata, remove original metadata, and update only the specified metadata headers. You can also specify whether to delete the source object after the copy operation completes.
<?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.
);