List only root objects (folders) in S3 - aws sdk v3 php

Given my S3 bucket, which contains images in such a structure:

root/portraits/portrait_001.jpg root/landscapes/landscape_001.jpg 

where root is my bucket, and there are no other files in my root, only those folders (objects), how can I get a list of only these objects?

 portraits/ landscapes/ 

I am familiar with using separator and prefix in ListObjects call.

If I do the following, I get no results:

 $objects = $s3->getIterator('ListObjects', array( 'Bucket' => $bucket, 'Delimiter' => '/', )); foreach($objects as $object) echo $object['Key'] . "\n"; 

If I do not use the delimiter, I get everything, obviously.

I cannot use the prefix because the objects that I need are root. Otherwise, I have no problem using the prefix to say list only the files in 'portraits /'

From my searches, I managed to find solutions of previous years that apply only to aws php sdk v1 or v2, and I had no luck in this (v3 is completely different)

Any suggestions? I feel that I am missing something simple, but looking through the documentation, I can not find anything to help me. As a last resort, I just need to manually declare an array

 $categories = ['portraits/', 'landscapes/'] 

But this is not ideal when I want to add more categories in the future, and I don’t have to worry about adding another category manually.

Any help would be greatly appreciated :)

Change - Solution

I must have looked for the wrong places during my dumps of objects, but in the end I saw common prefixes in the returned result of calling ListObjects with a delimiter '/', for example:

 $s3->listObjects(array('Bucket' => $bucket, 'Delimiter' => '/')); 
+6
source share
1 answer

Directories do not really exist on Amazon S3. However, the Management Console allows you to create folders, and paths are supported to create the illusion of directories.

For example, the bar.jpg object stored in the foo directory has a path to /foo/bar.jpg . The trick is that the object is actually called foo/bar.jpg , not just bar.jpg . Most users did not even notice the difference.

From the API, the possibility of directory listings is provided through the concept of CommonPrefixes , which look the same as directory paths and consist of a part of the object names ("keys") until the final slash.

See: Hierarchical key listing using prefix and delimiter

+4
source

All Articles