php-awsHow can I use PHP to list objects stored in AWS S3?
Using PHP, you can list objects stored in AWS S3 by using the listObjectsV2 method from the AWS SDK for PHP.
The following example code will list all objects stored in an S3 bucket:
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$s3 = new S3Client([
'region' => 'us-west-2',
'version' => 'latest',
'credentials' => [
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
]
]);
$objects = $s3->listObjectsV2([
'Bucket' => 'YOUR_S3_BUCKET_NAME'
]);
foreach ($objects['Contents'] as $object) {
echo $object['Key'] . PHP_EOL;
}
This example code will output the name of each object stored in the S3 bucket:
object1.txt
object2.txt
object3.txt
The code is broken down into the following parts:
- Require the autoloader from the AWS SDK for PHP:
require 'vendor/autoload.php';
- Use the S3Client class from the AWS SDK for PHP:
use Aws\S3\S3Client;
- Create a new S3Client instance with your AWS credentials:
$s3 = new S3Client([
'region' => 'us-west-2',
'version' => 'latest',
'credentials' => [
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
]
]);
- List the objects in the S3 bucket using the
listObjectsV2
method:
$objects = $s3->listObjectsV2([
'Bucket' => 'YOUR_S3_BUCKET_NAME'
]);
- Iterate over the list of objects and output the name of each object:
foreach ($objects['Contents'] as $object) {
echo $object['Key'] . PHP_EOL;
}
Helpful links
More of Php Aws
- How can I use PHP to connect to an Amazon Aurora database?
- How do I use PHP to create a ZIP file on AWS?
- How can I use the AWS API Gateway with PHP?
- How can I use AWS and Zksync together with PHP?
- How can I use Yum to install PHP on an Amazon EC2 instance?
- How can I use an AWS SQS Worker with PHP?
- How can I use AWS WAF to secure my PHP application?
- How can I use AWS PHP SDK without credentials?
- How do I generate an AWS Signature Version 4 with PHP?
- How do I determine the version of PHP I am running on AWS?
See more codes...