Delete objects using OSS SDK for PHP 2.0

Updated at:

You can temporarily or permanently delete an object from a versioning-enabled bucket based on whether you specify the version ID in the request. In addition, you can use the feature to delete an object, multiple objects, or objects whose names contain a specific prefix.

Usage notes

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

  • The oss:DeleteObject permission is required to delete an object. For more information, see Grant custom permissions to a RAM user.

Delete operations on a versioned bucket

When you call DeleteObject to delete an object from a versioned bucket, you must determine whether to specify a version ID in the request.

  • Delete an object without specifying a version ID (temporary deletion):

    By default, if you do not specify a version ID of the object in the request, OSS does not delete the current version of the object but adds a delete marker to the object as the new current version. If you perform the GetObject operation on the object, OSS identifies the current version of the object as a delete marker and returns 404 Not Found. In addition, x-oss-delete-marker = true and the x-oss-version-id header that indicates the version ID of the created delete marker are included in the response. If the value of the x-oss-delete-marker field is true, the version specified in the x-oss-version-id field is a delete marker.

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

  • Delete an object by specifying a version ID (permanent deletion):

    If you specify the version ID of the object that you want to delete in the request, OSS permanently deletes the version specified by the parameter in the versionId parameter in the params parameter. To delete a version whose ID is null, add params['versionId'] = “null” to params in the request.

Sample code

Delete an object with the specified version ID

The following sample code permanently deletes an object from a versioned bucket 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 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.
);

Temporarily delete an object without specifying its version ID

The following sample code temporarily deletes an object from a versioned bucket by sending a delete request in which no version ID is specified:

<?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.
);