Todos los productos
Search
Centro de documentos

Object Storage Service:Delete objects (PHP SDK V1)

Última actualización: Sep 22, 2026

Elimine un solo objeto, varios objetos por nombre, los objetos que coincidan con un prefijo o un directorio completo.

Aviso

Los objetos eliminados no se pueden recuperar. Proceda con precaución.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient.

  • Para eliminar un objeto, debe contar con el permiso oss:DeleteObject. Para obtener más información, consulte Attach a custom policy to a RAM user.

Eliminar un solo objeto

El siguiente código elimina un objeto llamado exampleobject.txt de un bucket denominado examplebucket:

<?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();
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";

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

    $ossClient->deleteObject($bucket, $object);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");          

Eliminar varios objetos

Puede eliminar hasta 1,000 objetos a la vez por nombre, por prefijo o por directorio.

También puede configurar reglas de ciclo de vida para eliminar objetos automáticamente. Para obtener más información, consulte Lifecycle rules based on last modification time.

Eliminar varios objetos con nombres específicos

El siguiente código elimina varios objetos por nombre:

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

// 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.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket = "examplebucket";

try {
   $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
   // Specify the full paths of the objects that you want to delete. The full paths cannot contain the bucket name.
   $objects = array();
   $objects[] = "exampleobjecta.txt";
   $objects[] = "exampledir/sampleobject.txt";
   $result = $ossClient->deleteObjects($bucket, $objects);

   foreach ($result as $info){
      $obj = strval($info);
      printf("Delete ".$obj." : Success" . "\n");
   }
   printf("Delete Objects : OK" . "\n");
} catch (OssException $e) {
   printf("Delete Objects : Failed" . "\n");
   printf($e->getMessage() . "\n");
   return;
}            

Eliminar varios objetos con un prefijo de nombre específico o dentro de un directorio determinado

El siguiente código elimina objetos por prefijo o elimina un directorio completo:

Aviso

Si OSS_PREFIX en el siguiente código se establece como una cadena vacía o NULL, se eliminan todos los objetos del bucket. Proceda con precaución.

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

// 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.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Set endpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket = "examplebucket";

try {
   $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
   $option = array(
      OssClient::OSS_MARKER => null,
      // To delete all objects whose names start with the prefix "src", set the prefix to "src". This operation deletes all non-folder objects with this prefix, the "src" folder, and all objects within the "src" folder.
      OssClient::OSS_PREFIX => "src",
      // To delete only the "src" folder and all objects in it, set the prefix to "src/".
      // OssClient::OSS_PREFIX => "src/",
   );
   $bool = true;
   while ($bool){
      // List and delete multiple objects.
      $result = $ossClient->listObjects($bucket,$option);
      $objects = array();
      if(count($result->getObjectList()) > 0){
         foreach ($result->getObjectList() as $key => $info){
            printf("key name:".$info->getKey().PHP_EOL);
            $objects[] = $info->getKey();
         }
         $delObjects = $ossClient->deleteObjects($bucket, $objects);
         foreach ($delObjects as $info){
            $obj = strval($info);
            printf("Delete ".$obj." : Success" . PHP_EOL);
         }
      }

      if($result->getIsTruncated() === 'true'){
         $option[OssClient::OSS_MARKER] = $result->getNextMarker();
      }else{
         $bool = false;
      }
   }
   printf("Delete Objects : OK" . PHP_EOL);
} catch (OssException $e) {
   printf("Delete Objects : Failed" . PHP_EOL);
   printf($e->getMessage() . PHP_EOL);
   return;
}
Nota

Si se lanza una excepción y se captura en un bloque try{}catch{}, los objetos no se eliminan. Llame a $e->getMessage para obtener el mensaje de error y analizar la causa.

Referencias

  • Para consultar el código de ejemplo completo sobre cómo eliminar objetos, revise el ejemplo de GitHub.

  • Para obtener más información sobre la operación de API que permite eliminar un solo objeto, consulte DeleteObject.

  • Para obtener más información sobre la operación de API que permite eliminar varios objetos, consulte DeleteMultipleObjects.