Copy objects using the OSS SDK for PHP 2.0
This topic describes how to use the new Copier module in OSS SDK for PHP 2.0 to copy files.
Usage notes
-
The sample code in this topic uses the region ID
cn-hangzhouof 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 from other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints. -
To copy an object, you must have the read permissions on the source object and read and write permissions on the destination bucket.
-
The source bucket and destination bucket must be located in the same region. For example, objects in a bucket located in the China (Hangzhou) region cannot be copied to a bucket located in the China (Qingdao) region.
-
Make sure that no retention policies are configured for the source bucket and the destination bucket. Otherwise, the following error message is returned: The object you specified is immutable.
-
In this topic, access credentials are obtained from environment variables. For information about how to configure access credentials for OSS SDK for PHP 2.0, see Configure access credentials for PHP.
Method
Copier
If you want to copy an object from a bucket to another bucket or modify the attributes of an object, you can call the CopyObject operation or the UploadPartCopy operation. The two operations are suitable for different scenarios:
-
The copy API (CopyObject) is suitable only for copying objects smaller than 5 GiB.
-
The (UploadPartCopy) operation is suitable for copying an object that is equal to or greater than 5 GiB in size. Take note that the operation does not support the(x-oss-metadata-directive) and (x-oss-tagging-directive) directives. To configure metadata and tagging during a multipart copy operation, you need additional implementation.
The new copy manager, Copier, introduced in OSS SDK for PHP 2.0, provides a high-level, unified interface for copying objects. It automatically selects the optimal copy API based on the request parameters, abstracting away underlying implementation details and interface differences. The common methods for 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. |
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:
|
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 instantiating a Copier client, you can specify configuration options to customize the default download behavior for all objects. You can also override these settings for an individual download by passing specific options with each download request.
-
Specify configuration parameters for Copier:
$c = $client->newCopier(['part_size' => 100 * 1024 * 1024]); -
Specify 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.
In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Product selection.
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
Reference
-
For the complete sample code for the copy manager, see the GitHub.