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 AwsS3S3Client;
$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.
2
Answers
I got it working using this approach
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.
There is an example in the SDK Example Code Library that deletes all objects in the bucket and then deletes the bucket, and one of the languages is PHP here. You do have to list everything in the bucket and delete all of the contents first, before you can delete the bucket. The full example can be cloned here.