S3 Upload: the simplest possible in Php

amazon_s3

Most applications still aren’t uploading its files to S3, and this post is part of a series that tries to show the easiest possible way to implement this in different languages and technologies. Here we’ll show the simplest way in Php. For TL;DR version, just fork the repo and try it locally.

In order to use this implementation, we need to get the Amazon Php SDK, and you can get it easily via Composer (Don’t know what’s Composer? Stop everything you’re doing and read this site), creating composer.json file in the project root folder with the following content:

After creating and modifying the config file, we need to download the dependencies, with this command:

Note that a vendor folder was created with AWS packages (in AWS SDK there are some extra libs accompanying Guzzle and Symfony Event Dispatcher).

Done with the dependencies, now it’s too easy. We have a very simple HTML form in the project with multipart/form-data encoding (index.php file), which submits to another file (upload.php) that receives form data and sends it straight to S3, without touching the local file system. We are using an existing bucket, but we could’ve also created a new bucket through the API.

Thus, we begin creating file index.php with the HTML form:

index.php

Then it’s time to create upload.php, which will handle the POST with data and store it in S3. Note that you’ll have to use your AWS account’s ACCESS_KEY and SECRET_KEY.

upload.php

At the end of the upload, we get the new file’s URL from HTTP Response and send it to users. That’s it! Your files and now being sent to S3 in a very simple and efficient manner!

The source code is available in my github.

21