Simple PHP code to push files to AWS S3

2 min readOct 14, 2017

So you have a web application, website or game with a PHP back-end. One of your use case is saving files to disk (images, Excel or what not). Its 2017 and you figure you should probably use a storage service instead of saving and serving files from your server.

Of course, you start Googling for a service. You land on Amazon Web Services Simple Storage, or AWS S3 for short. Pricing is good, company is solid, easy to setup via the app console. Ok sold! But now, how do you hook that up to your PHP back end? You find this beautiful, complete and huge SDK provided by Amazon: https://github.com/aws/aws-sdk-php.

Wait a minute, do you have to install the world to simply push a file to S3?

Fortunately, Donovan Schönknecht tackled this problem a few years ago and wrote a single php file which does it for you: https://github.com/tpyo/amazon-s3-php-class.

Here’s how I used it in my projects.

Step 1 — Copy the file

Just copy S3.php in your repo. Well actually the version in Donovan’s repo is outdated and does not use the right algorithm to sign requests. Fortunately, Rack Lin made a pull request with the right change. It hasn’t been merged though (Donavan doesn’t have time to maintain the repo). Rack Lin was kind enough to maintain his fork. So copy S3.php from his repo: https://github.com/racklin/amazon-s3-php-class.

Step 2 — Credentials for AWS

Create a php file with creds required, along with your region, and bucket name. Here’s a simple way to do that. Notice I conditionally load the constants only in prod. This allows me to fallback to local file storage instead (described in step 3) — very useful for development.

if (ENVIRONMENT == 'production') {
define('AWS_S3_KEY', 'XXXX');
define('AWS_S3_SECRET', 'XXXX');
define('AWS_S3_REGION', 'us-east-2');
define('AWS_S3_BUCKET', 'bucket');
define('AWS_S3_URL', 'http://s3.'.AWS_S3_REGION.'.amazonaws.com/'.AWS_S3_BUCKET.'/');
}

Step 3 — The code to push to AWS

Saving to AWS is very simple. Donavan provided simple static methods to allow this. In the case AWS is not available (i.e. dev environment) I fallback to saving to a file.

$tmpfile = $_FILES['file']['tmp_name'];
$file = $_FILES['file']['name'];
if (defined('AWS_S3_URL')) {
// Persist to AWS S3 and delete uploaded file
require_once('S3.php');
S3::setAuth(AWS_S3_KEY, AWS_S3_SECRET);
S3::setRegion(AWS_S3_REGION);
S3::setSignatureVersion('v4');
S3::putObject(S3::inputFile($tmpfile), AWS_S3_BUCKET, 'path/in/bucket/'.$file, S3::ACL_PUBLIC_READ);
unlink($tmpfile);
} else {
// Persist to disk
$path = 'path/to/user/files/'.$file;
move_uploaded_file($tmpfile, $path);
}

There you have it. Easy peasy PHP push to S3.

--

--

Martin Drapeau
Martin Drapeau

Written by Martin Drapeau

Founder of Activity Messenger, email and SMS for Sport & Leisure. Former CTO of Amilia. https://www.linkedin.com/in/martin-drapeau

Responses (3)