AWS SDK for PHP
Developer Guide

Configuring Amazon S3 Buckets with the AWS SDK for PHP Version 3

Cross-origin resource sharing (CORS) defines a way for client web applications that are loaded in one domain to interact with resources in a different domain. With CORS support in Amazon S3, you can build rich client-side web applications with Amazon S3 and selectively allow cross-origin access to your Amazon S3 resources.

For more information about using CORS configuration with an Amazon S3 bucket, see Cross-Origin Resource Sharing (CORS).

The following examples show how to:

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 Usage Patterns of the AWS SDK for PHP Version 3.

Get the CORS Configuration

Create a PHP file with the following code. First create an AWS.S3 client service, then call the getBucketCors method and specify the bucket whose CORS configuration you want.

The only parameter required is the name of the selected bucket. If the bucket currently has a CORS configuration, that configuration is returned by Amazon S3 as a CORSRules object.

Imports

use Aws\S3\S3Client; use Aws\Exception\AwsException;

Sample Code

$client = new S3Client([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2006-03-01' ]); try { $result = $client->getBucketCors([ 'Bucket' => $bucketName, // REQUIRED ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

Set the CORS Configuration

Create a PHP file with the following code. First create an AWS.S3 client service. Then call the putBucketCors method and specify the bucket whose CORS configuration to set, and the CORSConfiguration as a CORSRules JSON object.

Sample Code

$result = $client->putBucketCors([ 'Bucket' => $bucketName, // REQUIRED 'CORSConfiguration' => [ // REQUIRED 'CORSRules' => [ // REQUIRED [ 'AllowedHeaders' => ['Authorization'], 'AllowedMethods' => ['POST', 'GET', 'PUT'], // REQUIRED 'AllowedOrigins' => ['*'], // REQUIRED 'ExposeHeaders' => [], 'MaxAgeSeconds' => 3000 ], ], ] ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }