ParisNakitaKejser
ParisNakitaKejser

Reputation: 14849

Amazon S3 remove empty folder from PHP

I'm trying to remove objects and when all objects are removed i want to remove the main folder.

right now its work fine when i remove a object key in a folder, and when the folder are empty the folder will be removed, but when i hit the last main folder like (folder1/folder2/) and folder1 one are empty after folder2 are removed, i can't removed this folder.

my php code look like this.

$s3 = new S3Client([
    'version' => 'latest',
        'region'  => AMAZON_S3_REGION,
        'credentials' => [
            'key'    => AMAZON_KEY,
            'secret' => AMAZON_SECRET
        ]
]);

$response = $s3->listObjects([
    'Bucket' => AMAZON_S3_BUCKET,
    'Prefix' => $prefix_dir
]);

$keys = [];
foreach($response['Contents'] AS $val) {
    $keys[]['Key'] = $val['Key'];
}

$result = $s3->deleteObjects([
    'Bucket' => AMAZON_S3_BUCKET,
    'Objects' => $keys
]);

when i trying to remove the folder path alone after it i get a status-code 204 but why?

Upvotes: 0

Views: 788

Answers (1)

Justinas
Justinas

Reputation: 43481

Instead of deleteObjects try using deleteMatchingObjects and passing empty prefix or string matching some folder.

$s3->deleteMatchingObjects($bucket);
// or inner of folder
$s3->deleteMatchingObjects($bucket, 'folder1/');

Upvotes: 1

Related Questions