Wern Ancheta

Adventures in Web Development.

Getting Started With Amazon S3

| Comments

Amazon S3 is Amazon’s file storage service. It allows users to upload their files to their server, for later access or for sharing to other people. In this tutorial I’m going to walk you through how to use amazon s3 within your PHP applications.

First thing that you need to do is create a composer.json file and add the following:

1
2
3
4
5
{
    "require": {
        "aws/aws-sdk-php": "2.7.*@dev"
    }
}

Next execute composer install from your terminal to install the Amazon Web Service SDK.

Once the installation is done you can now create a tester.php file which we will use for interacting with the Amazon AWS API. Add the following code to the file:

1
2
3
4
5
6
<?php
require 'vendor/autoload.php';

use Aws\S3\Exception\S3Exception;
use Aws\Common\Aws;
?>

What the code above does is include the autoload file so that we can use the AWS SDK from our file. Next we set to use the Aws\S3\Exception\S3Exception and Aws\Common\Aws namespace so can access the different classes that are available in those namespaces. One of which classes is the Aws class which we can use to set the configuration options for the Bucket where we are trying to connect to. All we have to do is call the factory method and pass in the path to the configuration file:

1
2
3
<?php
$aws = Aws::factory('config.php');
?>

The configuration file contains the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'credentials' => array(
                    'key'    => 'YOUR_AWS_API_KEY',
                    'secret' => 'YOUR_AWS_API_SECRET',
                ),
                'region' => 'YOUR_BUCKET_REGION'
            )
        )
    )
);
?>

The configuration file basically just returns an array that contains the options that we need. First of those is the includes, which allows us to bootstrap the configuration file with AWS specific features. Next is the services where we specify the API credentials and region.

Uploading Files

Once that’s done we can now upload files to the s3 bucket of your choice by using the $aws object and calling the get method. This method takes up the name of the AWS service you want use. In this case were using s3 so we put in s3. Next we call the putObject method on the $s3 object and pass in the required parameters as an array. The required keys are Bucket, Key, Body and ACL. Bucket is the name of the bucket where you want to upload the file. Key is the path to the file. With s3 you don’t have to worry if the directory where you are uploading the file already exists. No matter how deep it is, s3 automatically creates the directories for you. Next is the Body which takes up the results of the fopen method call. This method takes up the path to the file in your local computer and the operation you want to perform. In this case we just want to read the file contents so we specify r. Next is the ACL or the Access Control List of an object. Its basically like a file permission. Here we specified public-read which means that the file can be read publically. For more information about ACL, you can check out this page. We wrap all of those code inside a try catch so we can handle errors gracefully.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$s3 = $aws->get('s3');

try{
    $s3->putObject(array(
        'Bucket' => 'NAME_OF_BUCKET',
        'Key' => '/path/to/file/filename',
        'Body' => fopen('/path/to/file_to_uploads', 'r'),
        'ACL' => 'public-read',
    ));
}catch (S3Exception $e){
    echo "There was an error uploading the file.<br>";
    echo $e->getMessage();
}
?>

Deleting Files

Next here’s how to delete existing files from your s3 bucket. This uses the deleteObject method which takes up the name of the bucket and the path to the file as its argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
try{

    $s3->deleteObject(array(
        'Bucket' => 'NAME_OF_BUCKET',
        'Key' => '/path/to/file/filename'
    ));

}catch(S3Exception $e){
    echo "There was an error deleting the file.<br>";
    echo $e->getMessage();
}
?>

Listing Buckets

Lastly here’s how to get a list of buckets that are currently in your Amazon Account:

1
2
3
4
5
6
7
<?php
$result = $s3->listBuckets();

foreach ($result['Buckets'] as $bucket) {
    echo "{$bucket['Name']} - {$bucket['CreationDate']}<br>";
}
?>

Conclusion

That’s it! In this tutorial you’ve learned how to work with Amazon S3 from within your PHP applications. Specifically, we’ve taken a look at how to upload files, delete files and list buckets.

Resources

Comments