Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete folder in Amazon S3 using PHP

I just started trying out Amazon S3 for hosting my website's images. I'm using the official Amazon AWS PHP SDK library.

Problem: How can I delete all files located in a S3 'folder'?
For example if I have a file named images/2012/photo.jpg, I want to delete all files whose filenames start with images/2012/.

like image 540
Nyxynyx Avatar asked Mar 11 '12 17:03

Nyxynyx


2 Answers

The best way to delete a folder from S3 with all its files is using the API deleteMatchingObjects()

$s3 = S3Client::factory(...);
$s3->deleteMatchingObjects('YOUR_BUCKET_NAME', '/some/dir');
like image 155
Luigi C. Avatar answered Sep 18 '22 22:09

Luigi C.


S3 does not have "folders" as you would traditionally think of them on a file system (some S3 clients just do a nice job making S3 appear to have folders). Those / are actually part of the file name.

As such, there is no "delete folder" option in the API. You would just need to delete each individual file that has the images/2012/... prefix.

Update:

This can be accomplished via the delete_all_objects method in the Amazon S3 PHP Client. Simply specify "/^images\/2012\//" as the regex prefix in the second argument (the first argument being your bucket name).

like image 22
nategood Avatar answered Sep 19 '22 22:09

nategood