Simple PHP code to push files to AWS S3

Martin Drapeau
Oct 14, 2017 · 2 min read

Step 1 — Copy the file

Step 2 — Credentials for AWS

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

$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);
}

Martin Drapeau

Written by

CTO at @AmiliaApp by day, dev hacker by night. I love to build companies with people and to build products with code. https://www.linkedin.com/in/martin-drapeau

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade