1. Code
  2. Cloud & Hosting
  3. AWS

How to Use Amazon S3 & PHP to Dynamically Store and Manage Files With Ease

Scroll to top
6 min read

Amazon S3 (Simple Storage Service) is a cloud-based object storage service offered by Amazon Web Services (AWS). In this article, we're going to discuss how you can use Amazon S3 to store and manage files easily with PHP. Amazon S3 provides a scalable, secure, and durable data storage service for a variety of use cases, including backup and recovery, content storage and distribution, data archiving, and big data analytics.

Being able to upload an unlimited number of files for hardly any money is great, but it would be even better if your users could upload files from your website. That way you wouldn't have to worry about the size of your web server for a second. Let's try!

Basically, our approach involves utilizing a conventional HTML file element and a user-friendly S3 PHP class to create a web page which allows users to upload files to an S3 bucket and obtain details about previously uploaded files.

If you haven't heard of Amazon S3 or don't have an account yet, I recommend that you go through the official documentation and set up an account with it.

Install the AWS SDK

Now, the first thing we'll need is a way for PHP to communicate with the S3 server. Luckily, AWS provides the official PHP SDK which we can use to communicate with S3 and perform different types of operations.

The aws/aws-sdk-php is the official software development kit (SDK) for PHP provided by Amazon Web Services (AWS). It allows developers to easily interact with various AWS services and build applications that integrate with these services. It provides different PHP classes for various AWS services such as Amazon S3, Amazon EC2, Amazon DynamoDB, Amazon SQS, and many others. Of course, in the context of this tutorial, we are really interested in the Amazon S3-related classes.

First things first, let's install the aws/aws-sdk-php package using composer. Run the following command in your terminal to install the aws/aws-sdk-php package.

1
$composer require aws/aws-sdk-php

Upon successful installation, it should generate the composer.json file as shown in the following snippet.

1
{
2
    "require": {
3
        "aws/aws-sdk-php": "^3.259"
4
    }
5
}

Build the HTML Upload Form

In this section, we'll quickly see how to build the HTML upload form.

Go ahead and create the index.php file with the following contents.

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
<html xmlns="http://www.w3.org/1999/xhtml">
3
    <head>
4
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5
        <title>S3 tutorial</title>
6
    </head>
7
8
    <body>
9
        <h1>Upload a file</h1>
10
11
        <p>Please select a file by clicking the 'Browse' button and press 'Upload' to start uploading your file.</p>
12
13
        <form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
14
          <input name="theFile" type="file" />
15
          <input name="Submit" type="submit" value="Upload">
16
        </form>
17
    </body>
18
</html>

The above file contains a form for uploading a file. The form contains an input element of type file, which enables the user to select a file to upload.

Finally, there's a submit button, which allows users to upload files to S3. It's important to note that, when a user clicks on the submit button, the form data will be submitted to the upload.php file as specified in the action attribute of the form element.

With that in place, our form is ready. Later in this article, we'll build the code of the upload.php file which actually uploads files to S3.

Set Up the Configuration File

Before we go ahead and implement the S3 upload feature, let's create the config.php file, which holds the S3 configuration information.

1
<?php
2
define("AWS_ACCESS_KEY_ID", "XXXXXXX");
3
define("AWS_ACCESS_KEY_SECRET", "XXXXXXXXXXXXXXXXXXXX");
4
define("AWS_ACCESS_REGION", "XXXXX");
5
define("AWS_BUCKET_NAME", "XXXXXXXX");
6
?>

The above PHP code defines four constants: AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY_SECRET, AWS_ACCESS_REGION, and AWS_BUCKET_NAME.

AWS_ACCESS_KEY_ID specifies the access key ID of your S3 account. The access key ID is a unique identifier which is used to authenticate requests made to the S3 API.

Next, AWS_ACCESS_KEY_SECRET specifies the secret access key of your S3 account. The secret access key is a private key which is used to sign requests made to the S3 API.

Next, AWS_ACCESS_REGION specifies the AWS region where the S3 bucket is located.

Finally, AWS_BUCKET_NAME specifies the name of the S3 bucket where files will be uploaded. This is the name of the bucket with which our PHP code will interact.

Once you create an AWS account, you will need to create an access key in the AWS Management Console to get the access key ID and secret access key. To get the region, go to the S3 service and look at the location of your bucket. The region will be listed in the endpoint URL for the bucket. It'll be something like eu-west-1. Finally, you will need to create an S3 bucket and give it a unique name, which should be your bucket name where all files will be uploaded by our PHP script.

Once you have all the details, make sure to set the correct values in the config.php file.

Implement the Upload Logic

In this section, we'll build the upload.php file, which contains the code to upload files to the S3 bucket.

Go ahead and create the upload.php file with the following contents.

1
<?php
2
require 'vendor/autoload.php';
3
require 'config.php';
4
5
use Aws\S3\S3Client;
6
7
$objAwsS3Client = new S3Client([
8
    'version' => 'latest',
9
    'region' => AWS_ACCESS_REGION,
10
    'credentials' => [
11
        'key'    => AWS_ACCESS_KEY_ID,
12
        'secret' => AWS_ACCESS_KEY_SECRET
13
    ]
14
]);
15
16
if (isset($_POST['Submit']) && $_POST['Submit'] == 'Upload') {
17
    if (isset($_FILES['theFile']) && $_FILES['theFile']['error'] === UPLOAD_ERR_OK) {
18
        $fileName = $_FILES['theFile']['name'];
19
        $fileTempName = $_FILES['theFile']['tmp_name'];
20
        $fileNameCmps = explode(".", $fileName);
21
        $fileExtension = strtolower(end($fileNameCmps));
22
        
23
        // sanitize file-name
24
        $newFileName = md5(time() . $fileName) . '.' . $fileExtension;
25
        
26
        try {
27
            $objAwsS3Client->putObject([
28
                'Bucket' => AWS_BUCKET_NAME,
29
                'Key'    => $newFileName,
30
                'Body'   => fopen($fileTempName, 'r'),
31
                'ACL'    => 'public-read'
32
            ]);
33
            
34
            echo "<strong>We successfully uploaded your file.</strong>";
35
        } catch (Aws\S3\Exception\S3Exception $e) {
36
            echo "There was an error uploading the file.\n";
37
        }
38
    }
39
}
40
?>

The above PHP code is responsible for uploading a file to an S3 bucket.

Firstly, we include the necessary dependencies. The config.php file contains the AWS credentials and the bucket name. The S3Client class is imported from the AWS SDK for PHP using the use statement.

Next, we've created a new S3Client object.

Next, we've checked whether the file was uploaded successfully. If so, it gets the name and temporary file name of the uploaded file, sanitizes the file name to prevent any malicious characters or extensions, and then tries to upload the file to the S3 bucket using the putObject method of the S3Client object. The uploaded file is given a unique name based on the current timestamp and its original file extension.

If the upload is successful, the code displays a success message. If there is an error, it displays an error message. You can also confirm it by looking into your S3 bucket, and the file should be there in case of successful upload.

Get a List of Uploaded Files From S3

In this section, we'll see how you can retrieve uploaded files from the S3 bucket.

Go ahead and create the list.php file with the following contents.

1
<?php
2
require 'vendor/autoload.php';
3
require 'config.php';
4
5
use Aws\S3\S3Client;
6
7
$objAwsS3Client = new S3Client([
8
    'version' => 'latest',
9
    'region' => AWS_ACCESS_REGION,
10
    'credentials' => [
11
        'key'    => AWS_ACCESS_KEY_ID,
12
        'secret' => AWS_ACCESS_KEY_SECRET
13
    ]
14
]);
15
16
try {
17
    $objects = $objAwsS3Client->listObjects(['Bucket' => AWS_BUCKET_NAME]);
18
19
    // loop through all files

20
    foreach ($objects['Contents'] as $object) {
21
        echo $object['Key'] . "<br>";
22
    }
23
} catch (Aws\S3\Exception\S3Exception $e) {
24
    echo "There was an error fetching data from S3: " . $e->getMessage();
25
}
26
?>

As you can see, it just lists all objects in an S3 bucket and displays their keys. We've used the listObjects method of the S3Client object to retrieve objects from S3.

Conclusion

Today, we discussed Amazon S3 (Simple Storage Service) which is a cloud-based object storage service. We also looked at some simple PHP code which allows the uploading of files to S3 using the AWS SDK for PHP. Apart from that, we also discussed how to retrieve files from S3.

Thumbnail image generated by OpenAI DALL-E 2.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.