Prevent overwriting files with the same name (PHP SDK V1)

Updated at:

By default, uploading an object overwrites any existing object with the same name. Set the x-oss-forbid-overwrite request header to true to block overwrites in simple upload and multipart upload.

Usage notes

  • The examples in this topic use the public endpoint for the China (Hangzhou) region. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information, see Regions and endpoints.

  • The examples create an OSSClient instance using an OSS endpoint. To create an OSSClient instance using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

How it works

The x-oss-forbid-overwrite header controls overwrite behavior for each upload request:

Header valueBehavior
Not specifiedExisting object with the same name is overwritten (default)
falseExisting object with the same name is overwritten
trueUpload is rejected if an object with the same name exists. OSS returns the FileAlreadyExists error.

Simple upload

Pass x-oss-forbid-overwrite: true in the options array when calling putObject. If an object with the same name already exists, OSS throws an OssException with the FileAlreadyExists error code.

<?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.
// Make sure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set before running this code.
$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket = "examplebucket";
$object = "exampledir/exampleobject.txt";
$content = "Hello OSS";

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

try {
    // Set x-oss-forbid-overwrite to true to reject uploads that would overwrite an existing object.
    // If the object already exists, OSS throws OssException with the FileAlreadyExists error code.
    $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

For multipart upload, set x-oss-forbid-overwrite: true in both initiateMultipartUpload and completeMultipartUpload. Setting the header only at initialization is not enough — the header must also be present when completing the 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.
// Make sure OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET are set before running this code.
$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket = "examplebucket";
$object = "exampledir/exampleobject.txt";
$uploadFile = "<yourLocalFile>";

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

try {
    // Step 1: Initialize the multipart upload with x-oss-forbid-overwrite set to true.
    $options = array(
        OssClient::OSS_HEADERS => array(
            'x-oss-forbid-overwrite' => 'true'
        ),
    );
    $uploadId = $ossClient->initiateMultipartUpload($bucket, $object, $options);

    // Step 2: 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,
        );
    }

    // Step 3: Complete the multipart upload with x-oss-forbid-overwrite set to true.
    // The header must be set here as well to enforce the no-overwrite constraint at completion.
    $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");