Copy objects using OSS SDK for PHP 2.0

Updated at:

This topic describes how to copy an object in a versioning-enabled bucket. You can call CopyObject to copy an object up to 1 GB in size and UploadPartCopy to copy an object larger than 1 GB in size.

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 copy an object, you must have the oss:GetObject and oss:PutObject permissions. For more information, see Grant a custom policy.

Examples

Copy an object

Note

You can call CopyObject to copy an object up to 1 GB in size from a source bucket to a destination bucket within the same region.

  • If you do not specify a version ID in the x-oss-copy-source header of a CopyObject request, the current version of the object is copied. If the current version of the object is a delete marker, OSS returns the HTTP 404 status code, which indicates that the object does not exist. You can specify a version ID in the x-oss-copy-source header to copy a specific object version. Delete markers cannot be copied.

  • You can copy a previous version of an object to the same bucket. The copied previous version becomes the current version of the object. This way, the previous version of the object is restored.

  • If versioning is enabled for the destination bucket, OSS generates a unique version ID for the destination object. The version ID is returned as the value of the x-oss-version-id header in the response. If versioning is disabled or suspended for the destination bucket, OSS generates a version whose version ID is null for the destination object and overwrites the previous version whose version ID is null.

The following sample code provides an example on how to copy an object:

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for 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 that can be used by other services to access 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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the source object.
];

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

// Obtain values from the parsed parameters.
$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.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations 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 an endpoint is provided.
}

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

// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key,
            sourceVersionId: "yourVersionId",// Specify the version ID of the source object.
);

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

Copy objects by using multipart copy

Note

To copy an object that is larger than 1 GB in size, you must split the object into parts and copy the parts by calling UploadPartCopy.

  • By default, UploadPartCopy uploads a part by copying data from the current version of an object. You can copy a specific version of an object by specifying the SourceVersionId parameter in an UploadPartCopy request.

  • If no version ID is specified in the request and the current version of the source object is a delete marker, OSS returns 404 Not Found. If the version ID is specified in the request and the specified version of the source object is a delete marker, OSS returns 400 Bad Request.

The following sample code provides an example on how to copy an object by using multipart copy:

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for 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 that can be used by other services to access 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.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the source object.
];

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

// Obtain values from the parsed parameters.
$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.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations 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 an endpoint is provided.
}
// Specify the endpoint.
$cfg->setEndpoint('http://oss-cn-hangzhou.aliyuncs.com');

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

// Initiate the multipart copy task.
$initRequest = new Oss\Models\InitiateMultipartUploadRequest(bucket: $bucket, key: $key);
$initResult = $client->initiateMultipartUpload($initRequest);

// Specify the name of the source bucket.
if (!empty($options["src-bucket"])) {
    $sourceBucket = $options["src-bucket"];
} else {
    $sourceBucket = $bucket;
}

// Query the metadata of the source object.
$headResult = $client->headObject(new Oss\Models\HeadObjectRequest(
    bucket: $sourceBucket,
    key: $srcKey
));

// Query the size of the source object.
$length = $headResult->contentLength;

// Specify the part size and calculate the number of parts.
$partSize = 1024 * 1024; // Specify the size of the parts. Unit: bytes. In this example, this parameter is set to 1 MB.
$partsNum = intdiv(num1: $length, num2: $partSize) + intval(1); // Specify the number of parts. The number is rounded up to the nearest integer.

// Create an empty array for the parts.
$parts = array();

// Traverse all parts and copy all parts.
for ($i = 1; $i <= $partsNum; $i++) {
    $partRequest = new Oss\Models\UploadPartCopyRequest(
        bucket: $bucket,
        key: $key,
        partNumber: $i,
        uploadId: $initResult->uploadId,
        sourceVersionId: "yourVersionId",// Specify the version ID of the source object.
    );

    // Specify the data range of the parts.
    $partRequest->sourceRange = getPartRange(totalSize: $length, partSize: $partSize, partNumber: $i);

    // Specify the name of the source bucket if the source bucket name is provided.
    if (!empty($options["src-bucket"])) {
        $partRequest->sourceBucket = $options["src-bucket"];
    }

    // Specify the name of the source object.
    $partRequest->sourceKey = $srcKey;

    // Perform the multipart copy operation.
    $partResult = $client->uploadPartCopy($partRequest);

    // Create an UploadPart object and add it to the part array.
    $part = new Oss\Models\UploadPart(
        partNumber: $i,
        etag: $partResult->etag,
    );
    array_push($parts, $part);
}

// Complete the multipart copy task.
$comResult = $client->completeMultipartUpload(
    new Oss\Models\CompleteMultipartUploadRequest(
        bucket: $bucket,
        key: $key,
        uploadId: $initResult->uploadId,
        completeMultipartUpload: new Oss\Models\CompleteMultipartUpload(
            parts: $parts
        ),
    )
);

// Display the result of the multipart copy task.
printf(
    'status code:' . $comResult->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $comResult->requestId . PHP_EOL .   // The request ID, which is used to debug or trace a request.
    'result:' . var_export($comResult, true) . PHP_EOL  // The detailed result of the multipart copy task.
);

/**
 * Query the data range of each part.
 *
 * @param int $totalSize The total size of the object that you want to copy.
 * @param int $partSize The size of the part.
 * @param int $partNumber Specify the number of the current part.
 * @return string The data range string of the part that is returned.
 */
function getPartRange(int $totalSize, int $partSize, int $partNumber): string
{
    $start = ($partNumber - 1) * $partSize; // Calculate the start position of the current part.
    =min($partNumber * $partSize-1, $totalSize-1); // Calculate the end position of the current part.
    return sprint('bytes %d-%d', $start,; // Format the parameters as a data range string.
}