Search code examples
phpobjectamazon-s3bucket

Delete object or bucket in Amazon S3?


I created a new amazon bucket called "photos". The bucket url is something like:

www.amazons3.salcaiser.com/photos

Now I upload subfolders containing files, into that bucket for example

www.amazons3.salcaiser.com/photos/thumbs/file.jpg

My questions are, does thumbs/ is assumed a new bucket or is it an object?

Then if I want to delete the entire thumbs/ directory need I first to delete all files inside that or can I delete all in one time?


Solution

  • In the case you are describing, "photos" is the bucket. S3 does not have sub-buckets or directories. Directories are simulated by using slashes in the object key. "thumbs/file.jpg" is an object key and "thumbs/" would be considered a key prefix.

    Dagon's examples are good and use the older version 1.x of the AWS SDK for PHP. However, you can do this more easily with the newest 2.4.x version AWS SDK for PHP which includes a helper method for deleting multiple objects.

    <?php
    
    // Include the SDK. This line depends on your installation method.
    require 'aws.phar';
    
    use Aws\S3\S3Client;
    
    $s3 = S3Client::factory(array(
        'key'    => 'your-aws-access-key',
        'secret' => 'your-aws-secret-key',
    ));
    
    // Delete the objects in the "photos" bucket with the a prefix of "thumbs/"
    $s3->deleteMatchingObjects('photos', 'thumbs/');