Delete objects (PHP SDK V2)

Updated at:

In a versioning-enabled bucket, OSS supports both temporary and permanent deletion of objects. The deletion type is determined by whether you specify a version ID. This feature lets you delete single or multiple objects, or objects with a specified prefix.

Usage notes

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

  • After versioning is enabled, you must have the oss:DeleteObjectVersion permission to delete objects. For more information, see Attach a custom policy to a RAM user.

How versioned deletion works

The deletion behavior in a versioning-enabled bucket is as follows:

  • Without a specified version ID (temporary deletion):

    When you delete an object without specifying a version ID, its current version is not deleted. Instead, OSS inserts a delete marker that becomes the new current version. When you perform a GetObject operation, OSS detects that the current version is a delete marker and returns404 Not Found. The response also includes thex-oss-delete-marker: true header and thex-oss-version-id of the new delete marker. A value oftrue forx-oss-delete-marker indicates that the version associated with the returned x-oss-version-id is a delete marker.

    To learn how to restore a temporarily deleted object, see Restore objects.

  • With a specified version ID (permanent deletion):

    When you perform a delete operation and specify a version ID in theparams, OSS permanently deletes the version specified by theversionId. To delete a version with a "null" ID, addparams['versionId'] = "null" to theparams.

Sample code

Delete with version ID

The following code permanently deletes an object by specifying its version ID:

<?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 for 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.
];

// Convert the parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract 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 ID of the object to delete.
);

// 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 can be used for debugging or tracking requests.
);

Delete without version ID

The following code temporarily deletes an object without specifying a version ID:

<?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 for 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.
];

// Convert the parameter descriptions to the long option format required by getopt.
// Add a colon ":" after each parameter to indicate that the parameter 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 provided.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Extract 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 can be used for debugging or tracking requests.
);