Todos os produtos
Search
Central de documentação

Object Storage Service:Excluir objetos (PHP SDK V1)

Última atualização: Jul 03, 2026

Exclua um único objeto, vários objetos por nome, objetos correspondentes a um prefixo ou um diretório inteiro.

Aviso

Objetos excluídos não podem ser recuperados. Proceda com cautela.

Observações de uso

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • Este tópico demonstra como crie uma instância OssClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Criar um OssClient.

  • Para exclua um objeto, você precisa da permissão oss:DeleteObject. Para mais informações, consulte Anexar uma política personalizada a um usuário RAM.

Excluir um único objeto

O código a seguir exclui um objeto chamado exampleobject.txt de um bucket chamado 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");          

Excluir vários objetos

Você pode exclua até 1.000 objetos por vez por nome, prefixo ou diretório.

Também é possível configure regras de ciclo de vida para exclua objetos automaticamente. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação.

Excluir vários objetos com nomes especificados

O código a seguir exclui vários objetos por nome:

<?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;
}            

Excluir vários objetos com o prefixo de nome de objeto especificado ou no diretório especificado

O código a seguir exclui objetos por prefixo ou remove um diretório inteiro:

Aviso

Se a variável OSS_PREFIX no código abaixo for defina como uma string vazia ou NULL, todos os objetos do bucket serão excluídos. Proceda com cautela.

<?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

Se uma exceção for lançada e capturada em um bloco try{}catch{}, os objetos não serão excluídos. Chame $e->getMessage para obter a mensagem de erro e analisar a causa.

Referências

  • Para obter o código de exemplo completo sobre exclusão de objetos, consulte o exemplo no GitHub.

  • Para mais informações sobre a operação de API para exclua um único objeto, consulte DeleteObject.

  • Para mais informações sobre a operação de API para exclua vários objetos, consulte DeleteMultipleObjects.