All Products
Search
Document Center

Object Storage Service:Delete objects (OSS SDK for PHP V2)

Last Updated:Aug 05, 2025

In a versioning-enabled bucket, OSS lets you temporarily or permanently delete an object depending on whether a versionId is specified. You can use this feature to delete a single object, multiple objects, or objects that have a specific prefix.

Precautions

  • The sample code in this topic uses the China (Hangzhou) region ID cn-hangzhou as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about the regions and endpoints that OSS supports, see OSS regions and endpoints.

  • To delete objects, you must have the oss:DeleteObject permission. For more information, see Grant custom permissions to a RAM user.

Delete behavior in versioning-enabled buckets

The delete behavior in versioning-enabled buckets is as follows:

  • If you do not specify a versionId (temporary deletion):

    If you perform a delete operation without specifying a versionId, the current version of the object is not deleted by default. Instead, a delete marker is inserted as the current version. When you perform a GetObject operation, OSS detects that the current version is a delete marker and returns 404 Not Found. In addition, the response contains header: x-oss-delete-marker = true and the version ID x-oss-version-id of the new delete marker. A value of true for x-oss-delete-marker indicates that the version corresponding to the returned x-oss-version-id is a delete marker.

    For more information about how to recover an object after the object is temporarily deleted, see Recover objects.

  • If you specify a versionId (permanent deletion):

    If you perform a delete operation and specify a versionId, OSS permanently deletes the object version specified by the versionId parameter in params. To delete a version whose ID is "null", add params['versionId'] = "null" to the params array.

Sample code

Delete an object by specifying a versionId

The following sample code shows how to permanently delete an object by specifying its versionId:

<?php

// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
    "key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];

// Transform the argument descriptions into the long option format required by getopt.
// Add a colon (:) after each argument to indicate that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Fetch values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

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

// Create a DeleteObjectRequest object to delete the specified object.
$request = new Oss\Models\DeleteObjectRequest(
            bucket: $bucket,
            key: $key,
            versionId:"yourversionid", // Specify the version number of the object to be deleted.
);

// Execute the delete object operation.
$result = $client->deleteObject($request);

// Print the deletion result.
// Output the HTTP status code and request ID to verify whether the deletion is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 204 indicates that the deletion is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or track requests.
);

Delete an object without specifying a versionId

The following sample code shows how to temporarily delete an object without specifying its versionId:

<?php

// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
    "key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];

// Transform the argument descriptions into the long option format required by getopt.
// Add a colon (:) after each argument to indicate that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Fetch values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

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

// Create a DeleteObjectRequest object to delete the specified object.
$request = new Oss\Models\DeleteObjectRequest(
            bucket: $bucket,
            key: $key,
);

// Execute the delete object operation.
$result = $client->deleteObject($request);

// Print the deletion result.
// Output the HTTP status code and request ID to verify whether the deletion is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 204 indicates that the deletion is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or track requests.
);