This topic describes how to use the new Copier module in PHP SDK V2 to copy files.
Precautions
The sample code in this topic uses the China (Hangzhou) region ID,
cn-hangzhou, and its public endpoint as an example. If you access OSS from another Alibaba Cloud service in the same region, you must use an internal endpoint. For more information about OSS regions and endpoints, see OSS regions and endpoints.To copy an object, you must have read permission for the source object and read and write permissions for the destination bucket.
Cross-region copy is not supported. For example, you cannot copy an object from a bucket in the China (Hangzhou) region to a bucket in the China (Qingdao) region.
When you copy an object, make sure that no retention policy is configured for the source or destination bucket. Otherwise, the The object you specified is immutable. error is reported.
This topic provides an example of how to read access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials for PHP.
Method definition
Introduction to the copy manager
When you need to copy an object from one bucket to another or modify the properties of an object, you can use the copy API or the multipart copy API. These two APIs are suitable for different scenarios. For example:
The copy API (CopyObject) is suitable only for copying objects smaller than 5 GB.
The multipart copy API (UploadPartCopy) supports copying objects larger than 5 GB but does not support the metadata directive (x-oss-metadata-directive) or the tagging directive (x-oss-tagging-directive) parameters. Therefore, when you use this API to copy an object, you must explicitly set the metadata and tags to be copied.
The new copy manager in PHP SDK V2, Copier, provides a universal copy API that abstracts the differences and implementation details of the underlying APIs. It automatically selects the appropriate API to copy an object based on the request parameters. The common methods of Copier are defined as follows:
final class Copier
{
...
public function __construct($client, array $args = [])
public function copy(Models\CopyObjectRequest $request, array $args = []): Models\CopyResult
}Request parameters
Parameter | Type | Description |
request | CopyObjectRequest | The request parameters for copying an object, which are the same as the request parameters of the CopyObject API. |
args | array | (Optional) Configuration options. |
The following table lists the common parameters of CopyObjectRequest.
Parameter | Type | Description |
bucket | string | The name of the destination bucket. |
key | string | The name of the destination object. |
sourceBucket | string | The name of the source bucket. |
sourceKey | string | The name of the source object. |
forbidOverwrite | string | Specifies whether to overwrite an object that has the same name in the destination bucket during the CopyObject operation. |
tagging | string | The tags of the object. You can specify multiple tags at a time, such as TagA=A&TagB=B. |
taggingDirective | string | Specifies how to set the tags for the destination object. Valid values:
|
The following table lists the common parameters of args.
Parameter | Type | Description |
part_size | int | The part size. Default value: 64 MiB. |
parallel_num | int | The number of concurrent upload tasks. Default value: 3. This parameter specifies the concurrency limit for a single call, not the global concurrency limit. |
multipart_copy_threshold | int | The threshold for using multipart copy. Default value: 200 MiB. |
leave_parts_on_error | bool | Specifies whether to retain the copied parts when the copy fails. By default, the copied parts are not retained. |
disable_shallow_copy | bool | Disables the shallow copy behavior. By default, shallow copy is used. |
When you instantiate a Copier instance, you can specify configuration options to customize the default object copy behavior. You can also specify these options for each copy API call to customize the behavior for a specific copy operation.
Set the configuration parameters for Copier:
$c = $client->newCopier(['part_size' => 100 * 1024 * 1024]);Set the configuration parameters for each copy request:
$c->copy( new Oss\Models\CopyObjectRequest( bucket: 'bucket', key: 'key', sourceBucket: 'src-bucket', sourceKey: 'src-key', ), args: ['part_size' => 100 * 1024 * 1024] );
When you copy an object, the metadataDirective property in CopyObjectRequest determines how the object metadata is copied. By default, the metadata of the source object is copied.
When you copy an object, the taggingDirective property in CopyObjectRequest determines how the object tags are copied. By default, the tags of the source object are copied.
This topic provides an example of how to read access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials for PHP.
Sample code
The following code copies an object from a source bucket to a destination bucket. By default, the metadata and tags of the source object are also copied.
<?php
// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description of command line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The name of the destination object. (Required)
"src-key" => ['help' => 'The name of the source object', 'required' => True], // The name of the source object. (Required)
];
// Convert the parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Verify that all required arguments are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information for the parameter.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required parameter is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The name of the destination object.
$srcKey = $options["src-key"]; // The name of the source object.
// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a Copier instance to perform copy operations.
$copier = $client->newCopier();
$dstKey = "multipart-copy-replace-empty-metadata-and-tagging-$key"; // The name of the destination object.
$copyRequest = new Oss\Models\CopyObjectRequest(
bucket: $bucket,
key: $dstKey,
sourceBucket: $bucket,
sourceKey: $srcKey
);
$copyRequest->metadataDirective = 'REPLACE'; // Replace the metadata.
$copyRequest->taggingDirective = 'REPLACE'; // Replace the tags.
$result = $copier->copy(request: $copyRequest);
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
'request id:' . $result->requestId . PHP_EOL // The request ID, which is used to debug or track requests.
);
Common scenarios
References
For the complete sample code for the copy manager, see the GitHub sample.