Search code examples
amazon-web-servicesamazon-s3aws-php-sdk

How to delete one AWS S3 "folder" using the PHP SDK?


I want to delete one folder and its entire contents in AWS S3 using the PHP-SDK. So the equivalent of rm -rf somepath in a normal file-system.

Let us assume that the folder is located at s3://somename/myfolder/1/1679666007/ and inside that has many files and other folders which also have other files inside.

I am trying this at the moment but without success because it is doing nothing, no errors as well is not deleting the folder with all the contents.

use Aws\S3\S3Client;

       $this>client = new S3Client();// is properly initialised but removed details for the example

        $this->client->deleteObject([
            'Bucket' => $this->config['bucket'],
            'Key' => rtrim($name,'/').'/', // the ending trailing slash is required for deleting directories in S3
        ]);

What is the proper way to do it?

I am using "aws/aws-sdk-php": "^3.191", php 8

I think it should exist some way to do it via API because we can do it in AWS S3 UI as well click delete the folder and confirm.

PS: I know that the concept of folder does not exist in S3 so please let us not try to fight over the terminology but be practical and get the concept done, deleting that path and all its subpaths in the most efficient performant way. Thanks in advance.


Solution

  • I got it working using this approach

            $this->client->deleteMatchingObjects($this->config['bucket'], $name); // deletes the files
            $this->client->deleteObject([
                'Bucket' => $this->config['bucket'],
                'Key' => rtrim($name,'/').'/', // the ending trailing slash is required for deleting directories in S3
            ]);
    

    I think the only drawback of the above method is that will delete also a file named with same name as the folder if it exists (very unlikely), other than that it is working very good.