Tous les produits
Search
Centre de documentation

Object Storage Service:Copier des fichiers (PHP SDK V1)

Dernière mise à jour :Aug 18, 2026

Cette rubrique explique comment copier un objet d'un bucket source vers un bucket de destination situé dans la même région. Le bucket de destination peut être identique ou différent du bucket source.

Notes d'utilisation

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour obtenir la liste des régions et des points de terminaison pris en charge, consultez la page Régions et points de terminaison.

  • Cette rubrique illustre la création d'une instance OSSClient avec un endpoint OSS. Pour découvrir d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des informations d'identification Security Token Service (STS), reportez-vous à la section Créer un OssClient.

  • Lorsqu'un utilisateur Resource Access Management (RAM) effectue une opération de copie, il doit disposer de l'autorisation oss:GetObject sur l'objet source. Il doit également posséder les autorisations oss:PutObject et oss:GetObject sur le bucket de destination. Pour plus d'informations sur l'attribution de stratégies personnalisées à un utilisateur RAM, consultez la page Exemples courants de stratégies RAM.

  • Les buckets source et de destination ne doivent pas avoir de politiques de rétention configurées. Dans le cas contraire, la copie échoue et renvoie l'erreur suivante : The object you specified is immutable.

  • La copie interrégionale n'est pas prise en charge. Par exemple, vous ne pouvez pas copier un objet d'un bucket situé en Chine (Hangzhou) vers un bucket situé en Chine (Qingdao).

Copier un petit fichier

L'exemple de code suivant montre comment utiliser la méthode $ossClient->copyObject pour copier un objet dont la taille est inférieure à 1 Go :

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// The endpoint of the China (Hangzhou) region is used in this example. Replace the value with the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the source bucket. Example: srcexamplebucket.
$from_bucket = "srcexamplebucket";
// Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/exampleobject.txt.
$from_object = "srcdir/exampleobject.txt";
// Specify the name of the destination bucket that is in the same region as the source bucket. Example: destexamplebucket.
// If you copy an object within the same bucket, make sure that the source and destination bucket names are the same.
$to_bucket = "destexamplebucket";
// Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/exampleobject.txt.
$to_object = "destdir/exampleobject.txt";

$options = array(
    'headers'=>array(
      // Specify whether to overwrite a destination object that has the same name. In this example, this parameter is set to true to prevent overwriting.
      // 'x-oss-forbid-overwrite' => 'true',
      // If the ETag of the source object matches the ETag that you specify, OSS copies the object and returns 200 OK.
      // 'x-oss-copy-source-if-match' => '5B3C1A2E053D763E1B002CC****',
      // If the ETag of the source object does not match the ETag that you specify, OSS copies the object and returns 200 OK.
      // 'x-oss-copy-source-if-none-match' => '5B3C1A2E053D763E1B002CC****',
      // If the specified time is the same as or later than the actual modification time of the object, OSS copies the object and returns 200 OK.
      // 'x-oss-copy-source-if-unmodified-since' => gmdate('2021-12-09T07:01:56.000Z'),
      // If the specified time is earlier than the actual modification time of the object, OSS copies the object and returns 200 OK.
      // 'x-oss-copy-source-if-modified-since' => gmdate('2021-12-09T07:01:56.000Z'),
      // Specify how to configure metadata for the destination object. In this example, this parameter is set to COPY to copy the metadata from the source object to the destination object.
      // 'x-oss-metadata-directive' => 'COPY',
      // Specify the server-side encryption algorithm that OSS uses to create the destination object.
      // 'x-oss-server-side-encryption' => 'KMS',
      // The customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
      // 'x-oss-server-side-encryption-key-id' => '9468da86-3509-4f8d-a61e-6eab****',
      // Specify the access permissions for the destination object. In this example, this parameter is set to private. This means only the object owner and authorized users have read and write permissions. Other users cannot access the object.
      // 'x-oss-object-acl' => 'private',
      // Specify the storage class of the object. In this example, this parameter is set to Standard.
      // 'x-oss-storage-class' => 'Standard',
      // Specify the tags for the object. You can specify multiple tags.
      // 'x-oss-tagging' => 'k1=v1&k2=v2&k3=v3',
      // Specify how to configure tags for the destination object. In this example, this parameter is set to COPY to copy the tags from the source object to the destination object.
      // 'x-oss-tagging-directive' => 'COPY',
    ),
);

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->copyObject($from_bucket, $from_object, $to_bucket, $to_object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");            

Copier un grand fichier

Pour les objets dépassant 1 Go, utilisez la copie multipartite (UploadPartCopy). Le processus se déroule en trois étapes :

  1. Appelez $ossClient->initiateMultipartUpload pour initialiser une tâche de copie multipartite.

  2. Appelez $ossClient->uploadPartCopy pour copier les parties. Toutes les parties, sauf la dernière, doivent avoir une taille supérieure à 100 Ko.

  3. Appelez $ossClient->completeMultipartUpload pour valider la tâche de copie multipartite.

L'exemple de code suivant montre comment effectuer une copie multipartite :

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new EnvironmentVariableCredentialsProvider();
// The endpoint of the China (Hangzhou) region is used in this example. Replace the value with the actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the source bucket.
$from_bucket = "yourSrcBucketName";
// Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/exampleobject.txt.
$from_object = "yourSrcObjectName";
// Specify the name of the destination bucket that is in the same region as the source bucket.
$to_bucket = "yourDestBucketName";
// Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/exampleobject.txt.
$to_object = 'yourDestObjectName';

// Set the part size in bytes as needed.
$part_size = 256*1024*1024;

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $objectMeta = $ossClient->getObjectMeta($from_bucket, $from_object);

    $length = $objectMeta['content-length'] + 0;

    // Initialize the multipart copy task.
    $upload_id = $ossClient->initiateMultipartUpload($to_bucket, $to_object);

    // Copy parts.
    $pieces = $ossClient->generateMultiuploadParts($length, $part_size);
    $response_upload_part = array();
    $copyId = 1;
    $upload_position = 0;

    foreach ($pieces as $i => $piece) {
        $from_pos = $upload_position + (integer)$piece['seekTo'];
        $to_pos = (integer)$piece['length'] + $from_pos - 1;
        $up_options = array(
            'start' => $from_pos,
            'end' => $to_pos,
              'headers'=>array(
                // If the ETag of the source object matches the ETag that you specify, OSS copies the object and returns 200 OK.
                // 'x-oss-copy-source-if-match' => '5B3C1A2E053D763E1B002CC****',
                // If the ETag of the source object does not match the ETag that you specify, OSS copies the object and returns 200 OK.
                // 'x-oss-copy-source-if-none-match' => '5B3C1A2E053D763E1B002CC****',
                // If the specified time is the same as or later than the actual modification time of the object, OSS copies the object and returns 200 OK.
                // 'x-oss-copy-source-if-unmodified-since' => gmdate('2021-12-09T07:01:56.000Z'),
                // If the specified time is earlier than the actual modification time of the object, OSS copies the object and returns 200 OK.
                // 'x-oss-copy-source-if-modified-since' => gmdate('2021-12-09T07:01:56.000Z'),
          ),
        );
        $response_upload_part[] = $ossClient->uploadPartCopy( $from_bucket, $from_object, $to_bucket, $to_object, $copyId, $upload_id, $up_options);
        $copyId = $copyId + 1;
    }

    // Complete the multipart copy.
    $upload_parts = array();
    foreach ($response_upload_part as $i => $etag) {
        $upload_parts[] = array(
            'PartNumber' => ($i + 1),
            'ETag' => $etag,
        );
    }
    $result = $ossClient->completeMultipartUpload($to_bucket, $to_object, $upload_id, $upload_parts);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");

Références

  • Copier un petit fichier

    • Pour consulter l'exemple de code complet relatif à la copie d'un petit fichier, rendez-vous sur GitHub.

    • Pour plus d'informations sur l'opération API permettant de copier un petit fichier, consultez la page CopyObject.

  • Copier un grand fichier

    • Pour consulter l'exemple de code complet relatif à la copie d'un grand fichier, rendez-vous sur GitHub.

    • Pour plus d'informations sur l'opération API permettant de copier un grand fichier, consultez la page UploadPartCopy.