All Products
Search
Document Center

Object Storage Service:Copy an object (OSS SDK for PHP V2)

Last Updated:Mar 19, 2026

Use the CopyObject method to copy an object less than 5 GiB from a source bucket to a destination bucket in the same region. The destination bucket can be the same as the source bucket or a different one.

Prerequisites

Before you begin, make sure that you have:

  • Read permissions on the source object

  • Read and write permissions on the destination bucket

  • Configured access credentials. For details, see Configure access credentials

Usage notes

  • Cross-region copy is not supported. For example, copying from China (Hangzhou) to China (Qingdao) fails.

  • If a retention policy is configured on the source or destination bucket, the operation returns the error: The object you specified is immutable.

  • The sample code uses cn-hangzhou as the region ID and a public endpoint by default. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For supported regions and endpoints, see OSS regions and endpoints.

Copy an object

<?php

// Load dependencies via Composer autoload.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line parameters.
$optsdesc = [
    "region"     => ['help' => 'The region where the bucket is located.',          'required' => true],
    "endpoint"   => ['help' => 'The endpoint used to access OSS.',                 'required' => false],
    "bucket"     => ['help' => 'The name of the destination bucket.',              'required' => true],
    "key"        => ['help' => 'The name of the destination object.',              'required' => true],
    "src-bucket" => ['help' => 'The name of the source bucket.',                   'required' => false],
    "src-key"    => ['help' => 'The name of the source object.',                   'required' => true],
];

// Build the long-option list for getopt (each option requires a value).
$longopts = array_map(fn($key) => "$key:", array_keys($optsdesc));
$options  = getopt("", $longopts);

// Validate required parameters.
foreach ($optsdesc as $key => $meta) {
    if ($meta['required'] && empty($options[$key])) {
        echo "Error: --$key is required. {$meta['help']}" . PHP_EOL;
        exit(1);
    }
}

// Extract parameter values.
$region = $options["region"];
$bucket = $options["bucket"];   // Destination bucket
$key    = $options["key"];      // Destination object key
$srcKey = $options["src-key"];  // Source object key

// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this script.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Initialize the SDK configuration.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create the OSS client.
$client = new Oss\Client($cfg);

// Build the copy request.
$request = new Oss\Models\CopyObjectRequest(bucket: $bucket, key: $key);
if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"];
}
$request->sourceKey = $srcKey;

// Execute the copy and handle errors.
try {
    $result = $client->copyObject($request);
    printf(
        "status code: %s\nrequest ID:  %s\n",
        $result->statusCode,  // 200 indicates success.
        $result->requestId    // Use this ID when troubleshooting with support.
    );
} catch (\Exception $e) {
    echo "Copy failed: " . $e->getMessage() . PHP_EOL;
    exit(1);
}

Parameters

ParameterTypeRequiredDescription
--regionstringYesRegion ID where the bucket is located, for example, cn-hangzhou
--bucketstringYesName of the destination bucket
--keystringYesKey (name) of the destination object
--src-keystringYesKey (name) of the source object
--endpointstringNoCustom endpoint. Omit to use the default public endpoint for the region
--src-bucketstringNoName of the source bucket

Key classes and methods

ElementDescription
EnvironmentVariableCredentialsProviderReads the AccessKey ID and AccessKey secret from environment variables
Config::loadDefault()Loads the default SDK configuration
CopyObjectRequestRequest object for CopyObject. Set sourceKey and optionally sourceBucket
copyObject($request)Executes the copy. Returns statusCode and requestId

What's next