删除桶

您可以使用 deleteBucket 接口删除桶,以下代码展示如何删除一个桶:

$bucket = '<your-bucket-name>';
try {
    $result = $s3Client->deleteBucket([
        'Bucket' => $bucket,
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

在删除桶前,必须先确保桶为空,否则会导致错误。

如果需要删除的桶不为空,需要在删除桶前删除该桶中所有的对象,示例代码如下:

$bucket = '<your-bucket-name>';
try {
   $objects = $s3Client->getIterator('ListObjects', ([
       'Bucket' => $bucket
   ]));
   echo "Keys retrieved!\n";
   foreach ($objects as $object) {
       echo $object['Key'] . "\n";
       $result = $s3Client->deleteObject([
           'Bucket' => $bucket,
           'Key' => $object['Key'],
       ]);
   }
   $result = $s3Client->deleteBucket([
       'Bucket' => $bucket,
   ]);
} catch (S3Exception $e) {
   echo $e->getMessage() . "\n";
}

如果需要删除的桶开启了版本控制,需要在删除桶前删除所有的对象版本,示例代码如下:

$bucket = '<your-bucket-name>';
try {
    $versions = $s3Client->listObjectVersions([
        'Bucket' => $bucket
    ])->search('Versions');
    echo "Keys retrieved!\n";
    foreach ($versions as $version) {
        echo $version['Key'] . "\n";
        echo $version['VersionId'] . "\n";
        $result = $s3Client->deleteObject([
            'Bucket' => $bucket,
            'Key' => $version['Key'],
            'VersionId' => $version['VersionId']
        ]);
    }
    $result = $s3Client->deleteBucket([
        'Bucket' => $bucket,
    ]);
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}