Todos os produtos
Search
Central de documentação

Object Storage Service:Copiar objetos com o OSS SDK for PHP 2.0

Última atualização: Aug 24, 2026

Este tópico descreve como usar o método CopyObject do OSS SDK for PHP 2.0 para copiar um objeto com tamanho inferior a 5 GiB de um bucket de origem para um bucket de destino na mesma região. O bucket de destino pode ser o próprio bucket de origem ou outro bucket.

Observações

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos em um bucket ocorre via endpoint público. Para acessar os recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints compatíveis, consulte OSS regions and endpoints.

  • Para copiar um objeto, você deve ter permissões de leitura no objeto de origem e permissões na lista de controle de acesso (ACL) do bucket de destino.

  • Não há suporte para cópia entre regiões. Por exemplo, não é possível copiar um objeto de um bucket na região China (Hangzhou) para um bucket na região China (Qingdao).

  • Ao copiar um objeto, verifique se nenhuma política de retenção está configurada no bucket de origem ou no bucket de destino. Caso contrário, o sistema retorna o seguinte erro: The object you specified is immutable.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para ver mais exemplos de configuração de credenciais de acesso, consulte Configure access credentials (PHP SDK V2).

Código de exemplo

Use o código de exemplo a seguir para copiar um objeto com tamanho inferior a 5 GiB de um bucket de origem para um bucket de destino:

<?php

// Include the autoload file to load dependencies.
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.
    "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 descriptions to a list of long options 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 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"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the destination bucket.
$key = $options["key"];       // Name of the destination object.
$srcKey = $options["src-key"]; // Name of the source object.

// Load 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 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);

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.

// Copy the source object.
$result = $client->copyObject($request);

// Output the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or trace a request.
);

Referências

  • Para obter o código de exemplo completo usado na cópia de objetos, visite o GitHub.