Monday, April 03, 2017

I've been working more with Amazon AWS and thought I'd share a bit of working PHP code that will take an uploaded form image and copy it to S3, effectively replacing the typical design which would write it to mounted disk space. There are several advantages to putting your images on S3 including having your images served without load on your primary processing server, and automated Glacier backups and Multi-zone reliability through configuration.

<?php
// ----------------------------------------------------------------------------
// s3-image-upload.php - send an image file uploaded via a form over to 
//                       your pre-configured S3 bucket. supports jpg and gif
// 2016-09-03 - halliwill - created
// ---------------------------------------------------------------------------

// -- used to assure file name uniqueness --
include_once('getnextsequence.php'); 

$bucket='pq-imgs';

// --- include the S3 load routine --
require 'aws-sdk/aws-autoloader.php';

// --- create an instance of the S3 client class ---
$s3 = new Aws\S3\S3Client([
'version' => '2006-03-01',
'region' => 'us-east-1'
]);

// --- move the file to a linux temp address ---
$temploc = "/tmp/" . "tmp_" . $_FILES['userfile']['name'];

if(!@copy($_FILES['userfile']['tmp_name'], $temploc)) 
die("Can't copy " . $_FILES['userfile']['name'] . " to " . $temploc . "
"); 

$image = $_FILES['userfile']['name'];
$increment = getNextSequence(); // -- retrieve file suffix - assure uniqueness -- 


// --- determine the file type ---
if( (stristr($image,".jpg")) or (stristr($image,".jpeg")) ) {
$type = "jpg";
} elseif (stristr($image,".gif")) {
$type = "gif";
} else {
echo "
image_upload: ERROR 1- Invalid filetype for " . $image . 
", only jpg and gif supported
";
exit;
} 

// --- create a unique file name for the destination file ---
if(strlen($image) > 18) { $filename = substr($image,0,18) . "-" . $increment . "." . $type; } 
else { $filename = $image . "-" . $increment . "." . $type; }

// -- $image is used by the routine that included this load routine, repoint it to the temp copy -- 
$image = $filename;

// --- check to make sure the file appears to have some content --- 
if($_FILES['userfile']['size'] <= 0) die ($_FILES['userfile']['name'] . " is empty.
"); 


// --- define the output path ---
$apath = $s3keyprefix . $filename;


try {
$upload = $s3->upload($bucket, $apath, fopen($_FILES['userfile']['tmp_name'], 'rb'), 'public-read');

// ------------------------------------------------------

} catch(Exception $e) { 
echo "error " . $e->getMessage() .
" uploading file " . 
FILES['userfile']['tmp_name'] . "
"; 
} 

?>