Search code examples
phpcodeigniteramazon-s3

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/.


Solution

  • 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).