Back to blog

Using thephpleague Flysystem with S3 and public read


For a project I had to store some files on Amazon S3 and I used the wonderful Flysystem package from The PHPLeague. While using this I encountered 2 problems:

1. Region lock

If your S3 bucket is created in any other region than US (although it seems impossible to do so) you might encounter problems like:

The bucket you are attempting to access must be addressed using the specified endpoint.

2. Public permissions

For my project the files uploaded need to have public access rights, meaning they can be viewed by anonymous users.

The client

At first we just start with the client as we can read in the Flysystem readme:


$client = S3Client::factory([
           'key' => 'your-aws-key',
            'secret' => 'your-aws-secret'
        ]);

 

Region

Before creating a new instance of the Filesystem we have to add one more option to the client, in this case the region the bucket was originally created.


$client->setRegion('your-region'); // e.g. eu-west-1

 

Filesystem with permissions

After that we create the Filesystem instance with an extra option so your files have public read rights.


$filesystem = new Filesystem(new Adapter($client, 'your-bucket-name', null, array('ACL' => 'public-read')));

 

Note the array with the ACL key is set to ‘public-read’.
When you write files now, they automatically will have the public-read permission and are accessible by anonymous users.

TL;DR


// Create a new S3 Client
$client = S3Client::factory([
           'key' => 'your-aws-key',
            'secret' => 'your-aws-secret'
        ]);

// Set the region where your S3 
$client->setRegion('your-region'); // e.g. eu-west-1

// Create a new Filesystem instance with the S3 client as adapter
$filesystem = new Filesystem(new Adapter($client, 'your-bucket-name', null, array('ACL' => 'public-read')));

// Upload a file with public-read permissions
$filesystem->write('sometextfile.txt', 'I am content on S3');

 

Labels: aws flysystem php s3 sdk thephpleague

One Response

  1. Thom on January 5, 2015

    Thanks!!! We couldn’t get it working for a customer, but setting the region did the job!

Drop a note