I've a bucket where users upload their content. here is how bucket looks like
bucket name : example-cdn
Directory under it : files
Now if user id is 2 and time is 1492693589, Now if user uploads an image the url will be
example-cdn/files/2/1492693589/image.png
Now if i try to delete that particular image then whole directory is deleted with the file.
here is the code
$s3 = new S3Client([
'version' => 'latest',
'region' => 'ap-south-1',
'credentials' => array(
'key' => '************',
'secret' => '*****************************'
)
]);
$s3->deleteObject(array('Bucket' => "example-cdn", 'Key' => "files/2/1492693589/image.png"));
Now When the above line executes it also delete the file folder and 2 folder. How can i only delete the image file image.png
Folders do not exist in Amazon S3.
Amazon S3 is a flat object store. It does not store files within folders/directories. However, files can be stored with a filename ('Key') that includes slashes, eg images/cat.jpg. This gives the illusion of directories, but doesn't actually create the directory.
For example, this command will create the images directory merely by naming a file as being in the (pretend) directory:
aws s3 cp cat.jpg s3://bucket/images/cat.jpg
When viewing the bucket in the management console, the images directory will be shown, and cat.jpg will be inside it. But it doesn't really exist!
This command will move the image to a different (pretend) directory:
aws s3p mv s3://bucket/images/cat.jpg s3://bucket/pictures/cat.jpg
This will make the images directory disappear and a new pictures directory will appear. Again, this is because the directories do not actually exist -- they are merely being shown that way because humans like the concept of directories.
When working through the AWS API, directories are known as common prefixes. They behave like directories, but do not exist.
But, you might ask, "What happens if I go to the Amazon S3 management console and click Create Folder? Surely that creates a folder!"
Actually, no. It merely creates a zero-byte file with the name of the directory, which forces the directory to appear. Deleting that zero-byte file will make the directory disappear because there is nothing in that path any more.
Bottom line: Directories don't exist, but feel free to move things in and out of them as if they do exist.
S3 buckets emulate folders. They don't actually exist. If there is no key with the prefix "files/2/", then there won't be a folder visible.
If you really want the "folders" to not disappear, make sure there is a file there to make them appear.
To clarify: this isn't unique to the sdk, this is just how the service works.