Build an uploader for S3

S3 is Amazon's "Simple Storage Service" for hosting content on the web. It allows developers to offload static content to their powerful content delivery network at low cost, to improve site performance. I've used S3 on a number of projects to host content, but one thing that only recently cropped up wad the notion of allowing users to upload their own content to the service from within any given site. To accomplish this I had to use a little bit of everything, including PHP and jQuery. But don't worry, if you don't want to use jQuery, this technique should still apply to other implementations.

As I said we will be using jQuery for this, and more specifically, the fantastic plugin Uplodify - a set of files that will enable simple uploading, and that will handle all the heavy lifting of file manipulation. So go ahead and download/unzip Uplodify, and then stick it on your server. I then used the following standard HTML to display the upload button.

<div id="upload_box">
	<div id="file_upload" name="theFile"></div>

Having done that, make sure to include jQuery, swifobject.js, and jquery.uplodify.[VERSION].js, and then add the following JS.

<script type="text/javascript">
    $(document).ready(function() {
        'uploader'  : 'uploadify.swf',
        'script'    : 'uploadify.php',
        'folder'    : 'uploads',
        'multi'	: true,
        'fileExt'   : '*.jpg;*.gif;*.png',
        'auto'      : true,
        'buttonImg' : 'button.jpg',
        'width'	: '86',
        'height'	: '28',
        'onSWFReady': function(){ $("#file_upload").show(); },

And that's the basic configuration needed to get Uploadify working. Now we need to enlist the help of a PHP class to enable us to interface with S3. That class allows you to do some pretty advanced stuff, and is a great solution all round for working with S3. In our case you just need to download that that and pop it in the same directory as the file uplodify.php.

And now we are finally ready to add the functionality that we've all been waiting for. Open uplodify.php and change:

echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);


$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

 $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
 $fileTypes  = str_replace(';','|',$fileTypes);
 $typesArray = split('\|',$fileTypes);
 $fileParts  = pathinfo($_FILES['Filedata']['name']);

 if (in_array($fileParts['extension'],$typesArray)) {
	if (!class_exists('S3'))require_once('S3.php');
	//AWS access info
	if (!defined('awsAccessKey')) define('awsAccessKey', '[ACCESS KEY]');
	if (!defined('awsSecretKey')) define('awsSecretKey', '[SECRET KEY]');
	//instantiate the class
	$s3 = new S3(awsAccessKey, awsSecretKey);

	//move the file
	$s3->putObject($_FILES['Filedata']['tmp_name'], "[BUCKET NAME]", $_FILES['Filedata']['name'], S3::ACL_PUBLIC_READ);

	echo "[BUCKET NAME]/".$fileName;
 } else {
 	echo 'Invalid file type.';

So what we've done there is replaced the part of the code that previously moved the uploaded file (with the imaginatively named move_uploaded_file() function), with some code to invoke a move to your S3 bucket. As you can see in the code above, the functions require some information that you will need to provide yourself such as your secret key - this can be found by logging in here.

And that's that! As I said above the class can be used for more advanced manipulation of your S3 buckets and account, so do go and explore some of the things you can do with that, and have fun uploading!

Tips & Tricks

You should host with Media Temple

I remember a few months back when I was faced with a dilemma, what hosting company should I go with for a certain client. I have had experience with some cheaper companies and to be honest for the price it isn't bad. However recently I have had problems with slow servers and a lot of downtime. Therefore I would like to recommend to anyone reading this to go with Media Temple. Now the cynics among you may believe that I am just trying to make money from referrals, but I can honestly say Media Temple is a great company. They provide an excellent service at what I think are reasonable prices.But it isn't just their service that is great, it's their attitude towards their customers. Their Twitter account is regularly updated by their staff, and should you have any questions or concerns you can send them a message via Twitter. Moreover they offer 24/7 phone support in case of any issues that may arise.

The back-end of their site is as slick a site as you ever did see. You can tell that they care about design, because the user experience is fantastic. The list of features is wonderful, and they are a caring company. For instance the other day I sent them a reply to a tweet where they were asking for interesting stuff, naturally I sent them a link to the article about Robert Noyce on this site. Soon after that tweeted the link and sent me a message of thanks asking for my address. Turns out they wanted to send me a T-Shirt for my support! Yes I know, big deal, but it's nice to know that they care, as opposed to just ignoring you after they get your money, or stating that MySQL issues are too complex to be dealt with by our online support kind of attitude.

So I can honestly say that Media Temple should be your host of choice; and if you don't believe me, then look at the list of clients on the website!