Tous les produits
Search
Centre de documentation

Object Storage Service:Supprimer des objets (PHP SDK V1)

Dernière mise à jour :Aug 18, 2026

Supprimez un objet unique, plusieurs objets par nom, les objets correspondant à un préfixe ou un répertoire entier.

Avertissement

La récupération des objets supprimés est impossible. Agissez avec prudence.

Notes d'utilisation

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus de détails sur les régions et endpoints pris en charge, consultez Régions et endpoints.

  • Cette rubrique explique comment créer une instance OssClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Créer un OssClient.

  • Pour supprimer un objet, vous devez disposer de l'autorisation oss:DeleteObject. Pour plus d'informations, consultez Attacher une politique personnalisée à un utilisateur RAM.

Supprimer un seul objet

Le code suivant supprime un objet nommé exampleobject.txt d'un bucket nommé 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");          

Supprimer plusieurs objets

Vous pouvez supprimer jusqu'à 1 000 objets simultanément par nom, par préfixe ou par répertoire.

Vous pouvez également configurer des règles de cycle de vie pour supprimer automatiquement les objets. Pour plus d'informations, consultez Règles de cycle de vie basées sur la dernière heure de modification.

Supprimer plusieurs objets avec des noms spécifiés

Le code suivant supprime plusieurs objets par nom :

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

Supprimer plusieurs objets avec le préfixe de nom d'objet spécifié ou dans le répertoire spécifié

Le code suivant supprime des objets par préfixe ou un répertoire entier :

Avertissement

Si OSS_PREFIX dans le code suivant est défini sur une chaîne vide ou NULL, tous les objets du bucket sont supprimés. Agissez avec prudence.

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

Si une exception est levée et interceptée dans un bloc try{}catch{}, les objets ne sont pas supprimés. Appelez $e->getMessage pour obtenir le message d'erreur et analyser la cause.

Références

  • Pour l'exemple de code complet relatif à la suppression d'objets, consultez l'exemple GitHub.

  • Pour plus d'informations sur l'opération API de suppression d'un seul objet, consultez DeleteObject.

  • Pour plus d'informations sur l'opération API de suppression de plusieurs objets, consultez DeleteMultipleObjects.