Amazon Web ServicesAWS S3File UploadsPHP

Amazon S3 PHP SDK Helper Class

Table of Contents

Introduction

Amazon S3 (Simple Storage Service), as its name implies, is a service that provides online cloud hosting for your files, separate from your site’s server. This might not seem like such a useful tool, as you can already just upload your files directly to your own site; why even deal with an external service?

AWS S3 has gained immense traction in recent years, and for good reason. Separating the files from your web server allows you to maintain a consistent environment on your local and remote server, which makes testing ideal.

Additionally, you are allowed unlimited space, while only paying for what you use; this is optimal for scaling. It also helps that their prices are dirt cheap.

Lastly, and possibly most importantly for some, is the added security benefits. You automatically eliminate the possibility of an attacker naming the file something that could mess with your server, along with the file itself somehow slipping through your file security, which is undoubtedly one of the more difficult aspects of security to fully master. Of course the file still goes in your server's temporary directory before uploading to S3, so the threat of the file executing something malicious still exists. I'm certainly not a security expert, but I'd imagine this would make a potential hacker's job much more difficult.

Why Did I Make This Class?

When I first started using the AWS S3 PHP SDK, I found myself constantly Googling how to do seemingly trivial commands, like uploading, downloading, renaming and deleting. There didn't seem to be any resources — including their own documentation — that had all of these commands on deck. Additionally, it was extremely cumbersome to have to look up and copy some of their lengthy commands every time I wanted to do a simple operation. Many times, it would take me more than an hour to figure out how to do the simplest of tasks.

For my own sanity, I started to create simple functions that I used in my project. I then wanted to share these functions to help developers using the SDK speed up development. I started writing a tutorial explaining all of the functions, but quickly realized that it would be better to just make a helper class instead. This page will contain the documentation for it, along with pragmatic examples for each method.

Getting Started

Start by downloading the AWS SDK for PHP. Then download my helper class on GitHub or BitBucket, your choice ;).

Create a file outside of your server's root directory (public_html, html, etc.) called s3_config.php. This is to ensure that your credentials are secure. Define constants for your key and secret like so:

define('AWS_KEY', 'enter-key-here');
define('AWS_SECRET', 'enter-secret-here');

Instantiating

require 's3_init.php';
$s3 = new S3('my-bucket', 'my-region');

Parameters


$bucket - Name of S3 bucket

$region - Name of bucket region

$verify (optional) - HTTP verify method. If not specified, it uses the default CA bundle provided by the operating system. Value can be true (default), false or a string with the path to a CA bundle. More details about it here.


There you go! Now you can easily use these semantic functions. That wasn't so bad, right?

Upload File

function uploadFile($path, $tmpFile, $contentType, $allowOverwrite = FALSE, $cacheLength = 31536000)

Usage


<form action="test.php" method="post" enctype="multipart/form-data">
 Select image to upload:
 <input type="file" name="fileToUpload" id="fileToUpload">
 <input type="submit" value="Upload Image" name="submit">
</form>
$file = $_FILES["fileToUpload"]["tmp_name"];
$dir = 'my-folder';
$name = "$dir/{$_FILES['fileToUpload']['name']}";
$type = 'image/jpeg';
$s3->uploadFile($name, $file, $type, TRUE);

Parameters


$path - Name of filename in S3

$tmpFile - File from an upload form

$contentType - Type of file, ex: 'image/jpeg'

$allowOverwrite (optional) - Allows overwriting if set to TRUE

$cacheLength (optional) - Cache length in seconds if specified; otherwise caches file for a year by default

Return


TRUE on successful file upload

FALSE on fail and echo error if file already exists or failed to upload

Download File

function downloadFile($path)

Usage


$s3->downloadFile('my-folder/file.jpg');

Parameter


$path - Filename in S3

Return


TRUE on successful download

FALSE on fail and echo error if file does not exist

Download Folder

function downloadFolder($path)

Usage


$s3->downloadFolder('my-folder');

Parameter


$path - Folder name in S3

Return


TRUE on successful download

FALSE on fail and echo error if folder in S3 does not exist, issues creating temp folder on server, issues deleting temp folder after download

Download Bucket

function downloadBucket($path = NULL)

Usage


$s3->downloadBucket();

Parameter


$path (optional) - If specified, method becomes equivalent to function downloadFolder()

Return


TRUE on successful download

FALSE on fail and echo error if folder in S3 does not exist, issues creating temp folder on server, issues deleting temp folder after download

Rename File

function renameFile($oldName, $newName)

Usage


$s3->renameFile('my-folder/old-name.jpg', 'my-folder/new-name.jpg');

Parameters


$oldName - Current filename

$newName - New filename

Return


TRUE on successful file rename

FALSE on fail and echo error if file does not exist, new filename is the same as old, new name already exists in S3, failed to rename file

Rename Folder

function renameFolder($oldName, $newName)

Usage


$s3->renameFolder('my-folder', 'my-folder-renamed');

Parameters


$oldName - Current folder name

$newName - New folder name

Return


TRUE on successful file rename

FALSE on fail and echo error if folder does not exist, new folder name is the same as old, new folder name already exists in S3, files failed to rename

Delete File

function deleteFile($path)

Usage


$s3->deleteFile('my-folder/file.jpg');

Parameter


$path - Filename to delete

Return


TRUE on successful delete

FALSE on fail and echo error if file does not exist, issue deleting file

Delete Folder

function deleteFolder($path)

Usage


$s3->deleteFolder('my-folder');

Parameter


$path - Folder to delete

Return


TRUE on successful delete

FALSE on fail and echo error if folder does not exist, error deleting any files in folder

Author - Daniel Marcus

Firmly believes that web technologies should take over everything. Enjoys writing tutorials about JavaScript and PHP.