All Products
Search
Document Center

Object Storage Service:Prevent objects from being overwritten by objects that have the same names by using OSS SDK for PHP

Last Updated:Mar 11, 2024

By default, if you upload an object that has the same name as an existing object, the existing object is overwritten by the uploaded object. This topic describes how to set the x-oss-forbid-overwrite request header to prevent objects from being overwritten by objects that have the same names in simple upload and multipart upload.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

Prevent objects from being overwritten by objects that have the same names in simple upload

The following sample code provides an example on how to prevent objects from being overwritten by objects that have the same names in simple upload:

<?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();
// In this example, the China (Hangzhou) region is used as the endpoint. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
$content = "Hello OSS";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

try{

   // Specify whether the object that is uploaded by calling the PutObject operation overwrites an existing object that has the same name. 
   // By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. 
   // If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. 
   // If x-oss-forbid-overwrite is set to true, an existing object with the same name cannot be overwritten. If you upload an object that has the same name as an existing object, the FileAlreadyExists error code is returned. 
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-forbid-overwrite' => 'true'
        ),
    );
    
    $ossClient->putObject($bucket, $object, $content, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");

Multipart upload

The following sample code provides an example on how to prevent objects from being overwritten by objects that have the same names in multipart upload:

<?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;
use OSS\Core\OssUtil;

// 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();
// In this example, the China (Hangzhou) region is used as the endpoint. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
$object = "<yourObjectName>";
$uploadFile = "<yourLocalFile>";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);

try{

    // Specify whether to overwrite the object that has the same name when the multipart upload task is initialized.     
    // By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. 
    // If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. 
    // If x-oss-forbid-overwrite is set to true, an existing object that has the same name cannot be overwritten. If you upload an object that has the same name as an existing object, the FileAlreadyExists error code is returned. 
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-forbid-overwrite' => 'true'
        ),
    );
    $uploadId = $ossClient->initiateMultipartUpload($bucket, $object, $options);

    // Upload parts. 
    $partSize = 1 * 1024 * 1024;
    $uploadFileSize = sprintf('%u',filesize($uploadFile));
    $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
    $responseUploadPart = array();
    $uploadPosition = 0;
    $isCheckMd5 = true;
    foreach ($pieces as $i => $piece) {
        $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
        $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
        $upOptions = array(
            $ossClient::OSS_FILE_UPLOAD => $uploadFile,
            $ossClient::OSS_PART_NUM => ($i + 1),
            $ossClient::OSS_SEEK_TO => $fromPos,
            $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
        );

        $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
    }
    $uploadParts = array();
    foreach ($responseUploadPart as $i => $eTag) {
        $uploadParts[] = array(
            'PartNumber' => ($i + 1),
            'ETag' => $eTag,
        );
    }    
    
    // Specify whether to overwrite the object that has the same name when the multipart upload task is complete. 
    // By default, if x-oss-forbid-overwrite is not specified, an existing object that has the same name is overwritten. 
    // If x-oss-forbid-overwrite is set to false, an existing object that has the same name is overwritten. 
    // If x-oss-forbid-overwrite is set to true, an existing object that has the same name cannot be overwritten. If you upload an object that has the same name as an existing object, the FileAlreadyExists error code is returned. 
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-forbid-overwrite' => 'true'
        ),
    );
    $ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts, $options);

} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");