List objects in a specific folder on Amazon S3 List objects in a specific folder on Amazon S3 php php

List objects in a specific folder on Amazon S3


You need to use Prefix to restrict the search to a specific directory (a common prefix).

$objects = $client->getIterator('ListObjects', array(    "Bucket" => $bucket,    "Prefix" => "your-folder/")); 


The answer is above however i figured i would supply a complete working example that can be copied and pasted directly into a php file and ran

use Aws\S3\S3Client;require_once('PATH_TO_API/aws-autoloader.php');$s3 = S3Client::factory(array(    'key'    => 'YOUR_KEY',    'secret' => 'YOUR_SECRET',    'region' => 'us-west-2'));$bucket = 'YOUR_BUCKET_NAME';$objects = $s3->getIterator('ListObjects', array(    "Bucket" => $bucket,    "Prefix" => 'some_folder/' //must have the trailing forward slash "/"));foreach ($objects as $object) {    echo $object['Key'] . "<br>";}


"S3Client::factory is deprecated in SDK 3.x, otherwise the solution is valid" said by RADU

Here is the updated solution to help others who come across this answer:

# composer dependenciesrequire '/vendor/aws-autoloader.php';//AWS access info  DEFINE command makes your Key and Secret more secureif (!defined('awsAccessKey')) define('awsAccessKey', 'ACCESS_KEY_HERE');///  <- put in your key instead of ACCESS_KEY_HEREif (!defined('awsSecretKey')) define('awsSecretKey', 'SECRET_KEY_HERE');///  <- put in your secret instead of SECRET_KEY_HEREuse Aws\S3\S3Client;$config = [    's3-access' => [        'key' => awsAccessKey,        'secret' => awsSecretKey,        'bucket' => 'bucket',        'region' => 'us-east-1', // 'US East (N. Virginia)' is 'us-east-1', research this because if you use the wrong one it won't work!        'version' => 'latest',        'acl' => 'public-read',        'private-acl' => 'private'    ]];# initializing s3$s3 = Aws\S3\S3Client::factory([    'credentials' => [        'key' => $config['s3-access']['key'],        'secret' => $config['s3-access']['secret']    ],    'version' => $config['s3-access']['version'],    'region' => $config['s3-access']['region']]);$bucket = 'bucket';$objects = $s3->getIterator('ListObjects', array(    "Bucket" => $bucket,    "Prefix" => 'filename' //must have the trailing forward slash for folders "folder/" or just type the beginning of a filename "pict" to list all of them like pict1, pict2, etc.));foreach ($objects as $object) {    echo $object['Key'] . "<br>";}