Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thomaskanzig/0294864c9931031d9a01969a27046e32 to your computer and use it in GitHub Desktop.
Save thomaskanzig/0294864c9931031d9a01969a27046e32 to your computer and use it in GitHub Desktop.
Get, list and delete objects from AWS S3 Bucket

Get, list and delete objects from AWS S3 Bucket

As requirement, install the AWS SDK for PHP library to connect AWS S3.
First of all you need to connect to your AWS S3:

require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$config =
[
    'version' => 'latest',
    'region' => '',
    'endpoint' => '[cluster-url]',
    'credentials' =>
    [
        'key' => '[access-key]',
        'secret' => '[secret-key]',
    ],
];

$client = new \Aws\S3\S3Client($config);

List objects:

$result = $client->listObjects([
    'Bucket' => 'bucket-name',
    'Prefix' => 'sub/directory/'
]);

foreach ($result['Contents'] as $key => $object) {
    // Is the value of prefix.
    if (0 === $key) {
        continue;
    }

    echo $object['Key'] . "<br>";
}

Get object:

$object = $client->getObject(array(
    'Bucket' => 'bucket-name',
    'Key'    => 'sub/directory/image.jpg'
));

Delete object:

$client->deleteObject([
    'Bucket' => 'bucket-name',
    'Key'    => 'sub/directory/image.jpg'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment