Zend certified PHP/Magento developer

CloudSpring: Getting Started with the AWS PHP SDK

Getting Started with AWS PHP SDK

Amazon AWS S3 is a robust storage solution for the internet. It can be used to store and retrieve any amount of data, at any time, from anywhere on the web. With S3 you get access to highly scalable, reliable, secure, fast, inexpensive infrastructure for your web app.

In the coming weeks I’ll be creating a series of tutorials that show you how to do amazing things using Amazon S3 and other Amazon AWS services. This article is designed to give you a running start in using Amazon Web Services.

Amazon has provided powerful SDK support for many different platforms, including PHP. In this article you’ll learn how to start using the AWS SDK for PHP using practical examples.

Prerequisites

Most web hosts have a PHP setup that will support the SDK without any additional configuration, but if you have any trouble with any of the examples below, please see the Resources at the end of this article.

In addition to a regular old web host, you’ll also need an Amazon AWS account. Set one up at: http://aws.amazon.com

Also, you’ll need to make sure you have the Amazon AWS S3 service enabled in your account. All of my examples will utilize that service.

Installation Configuration

1) Download
Start by getting the SDK files on your web server. There are a few ways to accomplish this. My favorite is to download the SDK and upload the files to your web server. Easy, right? You can also use PEAR and a few other methods to install the SDK. You can download the latest version here: http://pear.amazonwebservices.com/get/sdk-latest.zip

For the purposes of this article, I’m going to upload the SDK to a folder in the root of my web called “awssdk”.

2) Rename the Config File

Once your files are uploaded, you need to update your configuration file. The first step is to change the name of the config file from config-sample.inc.php to: config.inc.php

3) Config File Settings
Now open the config file and insert your own credentials. There 10 or more constants being defined in this file. For now you only need to update three of them:

define('AWS_KEY', 'ENTER YOUR AWS KEY HERE');
define('AWS_SECRET_KEY', 'ENTER YOUR AWS SECRET KEY HERE');
define('AWS_ACCOUNT_ID', 'ENTER YOUR AWS ACCOUNT ID HERE');

Finding these values is easy:

  • Simply sign-in to your AWS management console.
  • Click “Account” in the very top navigation menu.
  • Click “Security Credentials”.
  • Scroll down to find your AWS Key and Secret Key. Your Secret Key will be hidden until you click “View”.
  • Scroll down even further to find your account number.

Hello Buckets

Start by creating a file called fun.php in the same folder where I uploaded the SDK. So far, here’s what your directory structure should look like:

/awssdk/sdk.class.php
/awssdk/config.inc.php
/awssdk/fun.php
/awssdk/utilities
/awssdk/services
/awssdk/lib
/awssdk/extensions
/awssdk/.... (a few more directories)

We’ll be doing all our coding in fun.php

1) Include the AWS SDK

In order to use the SDK, it needs to be included in our PHP code. If you setup your file structure like I demonstrated above, the following code should work to include the SDK:

?php
require_once 'sdk.class.php';

2) Create a Bucket

The easiest test you can do in the AWS SDK is to create a bucket in S3. An S3 bucket is like a “domain” for file storage. Once we have a bucket we can start creating, editing, and deleting files using PHP. Here’s the code:

?php
require_once 'sdk.class.php';
// Create the s3 Object from the SDK
$s3 = new AmazonS3();
// Run the Method: Create Bucket.
// Arg 1: 'my-unique-bucket-name' is the name of your new bucket.
// Arg 2: The geographical region where your data will be stored.
// Arg 3: Tells Amazon to make your files readable by anyone like regular files hosted on a web server.
$response = $s3-create_bucket('my-unique-bucket-name', AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
// The response comes back as a Simple XML Object
// In this case we just want to know if everything was okay.
// If not, report the message from the XML response.
if ((int) $response-isOK()) {
    echo 'Created Bucket';
} else {
    echo (string) $response-body-Message;
}

Here are few things to remember when creating S3 buckets:

  • Bucket names are used for domain names, so you can only use numbers, letters, and dashes.
  • Bucket names are must be unique across all Amazon AWS users. In other words, ‘my-unique-bucket-name’ is already taken (by me) so you need to choose your own unique bucket names.

2) List Buckets

Now that you’ve created a bucket, you can use the following example to list all the buckets in your account:

?php
$s3 = new AmazonS3();
$response = $s3-list_buckets();
foreach ($response-body-Buckets[0] as $bucket) {
    echo (string) $bucket-Name."br /";
}

Hello World

Now that we have a bucket, we’re ready to take on the world. The following example demonstrates how to create simple text file in an AWS bucket:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
//        In this case we're specifying the "body" option
//        and the ACL setting to allow this file to be read by anyone.
$response = $s3-create_object('my-unique-bucket-name', 'test1.txt', array(
'body' = 'Hello world. Nice to meet you.',
'acl'=AmazonS3::ACL_PUBLIC,
));
if ((int) $response-isOK()) echo 'I Created a File!';

To test if your file uploaded, try accessing it using its URL: http://your-unique-bucket-name-here.s3.amazonaws.com/test1.txt

Use Case 1: Public Content Delivery

The most basic usage for Amazon’s S3 service is to provide storage and delivery for web content like images, videos, and other media. You can serve any kind of content using S3, including streaming video and regular HTML web pages. Amazon handles all the working of making sure your files are safe and that they are always delivered fast, all you need to do is get your files into an S3 bucket!
We’ve already demonstrated how to create a simple text file in S3. The following examples demonstrate a few additional options for getting files up into your S3 bucket:

1) Upload a File from Your Server

For this example, upload a file called “file.jpg” into your awssdk folder. Our goal is to upload the file from your server to the S3 bucket:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
//        In this case we're specifying the "fileUpload" option (a file on your server)
//        and the ACL setting to allow this file to be read by anyone.
$response = $s3-create_object('my-unique-bucket-name', 'in_the_cloud.jpg', array(
'fileUpload'=__DIR__.'/file.jpg',
'acl'=AmazonS3::ACL_PUBLIC,
));
// Check if everything is okay.
if ((int) $response-isOK()) echo 'I Uploaded a File from My Server!';

As with the previous example, you can verify your upload by previewing it in your browser: http://my-unique-bucket-name-here.s3.amazonaws.com/in_the_cloud.jpg

2) Upload a File from Another Website

Sometimes you want to get a file from another URL into S3. This is really easy:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
//        In this case we're specifying the "body" option (opening a file from the web),
//        we're setting the contentType of the file so browsers know its an image,
//        and we're setting the ACL setting to allow this file to be read by anyone.
$response = $s3-create_object('my-unique-bucket-name', 'from_a_url.gif', array(
'body'=file_get_contents('http://www.google.com/logos/logo_newyear.gif'),
'contentType'='image/gif',
'acl'=AmazonS3::ACL_PUBLIC,
));
// Check if everything is okay.
if ((int) $response-isOK()) echo 'I Uploaded a File from the Web!';

2) Generate a Thumbnail
Let’s say you want to generate a thumbnail from an image and you know the URL of the image. This example will work:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create a thumbnail from a URL
$originalImage = imagecreatefromgif('http://www.google.com/logos/logo_newyear.gif');
$new_height = 30;
$width = imagesx($originalImage);
$height = imagesy($originalImage);
$new_width = round(($width * $new_height) / $height);
$imageResized = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($imageResized, $originalImage, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the image in a temp file.
$tempfilename = tempnam(__DIR__, "newImage");
ImageJpeg($imageResized,$tempfilename,100);
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
//        In this case we're specifying the "body" option (opening the temp image file we created),
//        we're setting the contentType of the file so browsers know its an image,
//        and we're setting the ACL setting to allow this file to be read by anyone.
$response = $s3-create_object('my-unique-bucket-name', 'from_php_script.jpg', array(
'body'=file_get_contents($tempfilename),
'contentType'='image/jpeg',
'acl'=AmazonS3::ACL_PUBLIC,
));
// Delete the temporary file.
unlink($tempfilename);
// Check if everything is okay.
if ((int) $response-isOK()) echo 'I Uploaded a File Created with PHP!';

Use Case 2: Protected Content Delivery

In some cases, you want to add a little bit of security to the images your store on S3. S3 provides a number of ways to add security, but one of the easiest ways is to generate time-limited URLs.

Time-limited URLs are easy to generated, and they allow you to allow your users to download content using a secure URL that will expire as soon as you want it to. In some cases, you might want your content to expire within a few minutes.
This works great for showing protected images on a website. In other cases you might want to allow the file to be downloaded for a few days or weeks, which may work better for delivering links to downloads by email.

The first step in creating a secure file, is to upload a file that cannot be accessed by default on the internet:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
//        In this case we're specifying the "fileUpload" option (a file on your server)
//        and the ACL setting to prevent this file from being read by anyone on the interent.
$response = $s3-create_object('my-unique-bucket-name', 'in_the_cloud_private.jpg', array(
'fileUpload'=__DIR__.'/file.jpg',
'acl'=AmazonS3::ACL_PRIVATE,
));
// Check if everything is okay.
if ((int) $response-isOK()) echo 'I Uploaded a PRIVATE File from My Server!';

The regular URL for this file would be: http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud_private.jpg

But if you try that URL, you’ll get an access denied error. This is good because we want this file to be protected. But let’s say we wanted to send a link to this file to someone by email. We want to make it easy for them to download, but we don’t want that link to get out on some forum somewhere where it can be downloaded anytime by anyone.
The solution is to create a link to the file that expires in 24 hours. Here’s how easy it is:

?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
//Generate a Secure URL
$secureURl = $s3-get_object_url(
    'my-unique-bucket-name',
    'in_the_cloud.jpg',
    '24 Hours'
);
echo $secureURl;

This will generate a URL that looks like this: http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud.jpg?AWSAccessKeyId=AKIAINUIRH7EHMGFBWQQExpires=1313027791Signature=G2IlL3fWpi0MyvDcuplbNeF2uNg%3D

This link will provide access to the file for 24 hours, after that the user will get an Access Denied error.

Unlimited Possibilities

Hopefully after trying these examples you feel comfortable creating and accessing files using Amazon’s S3 storage service.

We’ve only scratched the surfaces of what is possible. In the coming weeks I’ll take you deeper into many of the ways you can use S3 to do amazing things with your websites and web applications.

If you have questions or suggestions about using S3 as I’ve described, please open a discussion below!

AWS SDK RESOURCES FOR PHP