Menu
AWS SDK for PHP
Developer Guide

Creating and Using Amazon S3 Buckets with AWS SDK for PHP version 3

The following examples show how to:

  • Return a list of buckets owned by the authenticated sender of the request using ListBuckets.

  • Create a new bucket using CreateBucket.

  • Add an object to a bucket using PutObject.

All the example code for the AWS SDK for PHP version 3 is available here on GitHub.

Credentials

Before running the example code, configure your AWS credentials, as described in Credentials for the AWS SDK for PHP Version 3. Then import the AWS SDK for PHP, as described in Basic Use of the AWS SDK for PHP version 3.

Imports

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

List Buckets

Create a PHP file with the following code. First create an AWS.S3 client service that specifies the AWS Region and version. Then call the listBuckets method, which returns all Amazon S3 buckets owned by the sender of the request as an array of Bucket structures.

Sample Code

//Create a S3Client $s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); //Listing all S3 Bucket $buckets = $s3Client->listBuckets(); foreach ($buckets['Buckets'] as $bucket){ echo $bucket['Name']."\n"; }

Create a Bucket

Create a PHP file with following code. First create an AWS.S3 client service that specifies the AWS Region and version. Then call the createBucket method with an array as the parameter. The only required field is the key 'Bucket', with a string value for the bucket name you want to create. However, you can specify the AWS Region with the 'CreateBucketConfiguration' field. If successful, this method returns the 'Location' of the bucket.

Sample Code

$BUCKET_NAME='<BUCKET-NAME>'; //Create a S3Client $s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); //Creating S3 Bucket try { $result = $s3Client->createBucket([ 'Bucket' => $BUCKET_NAME, ]); }catch (AwsException $e) { // output error message if fails echo $e->getMessage(); echo "\n"; }

Put an Object in a Bucket

To add files to your new bucket, create a PHP file with the following code.

In your command line execute this file and pass in the name of the bucket where you want to upload your file as a string, followed by the full file path to the file you want to upload.

Sample Code

$USAGE = "\n" . "To run this example, supply the name of an S3 bucket and a file to\n" . "upload to it.\n" . "\n" . "Ex: php PutObject.php <bucketname> <filename>\n"; if (count($argv) <= 2){ echo $USAGE; exit(); } $bucket = $argv[1]; $file_Path = $argv[2]; $key = basename($argv[2]); try{ //Create a S3Client $s3Client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); $result = $s3Client->putObject([ 'Bucket' => $bucket, 'Key' => $key, 'SourceFile' => $file_Path, ]); } catch (S3Exception $e) { echo $e->getMessage() . "\n"; }