PHP: How to Upload a File to AWS S3

Updated: January 13, 2024 By: Guest Contributor Post a comment

Introduction

Amazon Web Services (AWS) Simple Storage Service (S3) is a scalable, high-speed, web-based cloud storage service designed for online backup and archiving of data and applications. Integrating AWS S3 with a PHP application allows for the storing of user-generated content, backups, and static assets like images and documents. In this tutorial, you’ll learn step by step how to upload a file to AWS S3 using PHP.

Prerequisites

  • A PHP environment set up with at least PHP 5.3.3 compatibility.
  • Composer installed for dependency management.
  • An AWS account with S3 configured.
  • Access Key ID and Secret Access Key for your AWS account.
  • An S3 bucket where files will be uploaded.

The Steps

Step 1: Install AWS SDK for PHP

First, you’ll need to install the AWS SDK for PHP via Composer. The AWS SDK provides convenient methods for interacting with AWS services including S3.

composer require aws/aws-sdk-php

Once you’ve installed the AWS SDK, be sure to include the autoload file in your PHP script.

require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

Step 2: Configure AWS S3 Client

Create an S3 client instance with your credentials. This includes your Access Key ID, Secret Access Key, and the region where your S3 bucket is hosted.

$s3Client = new S3Client([
    'version' => 'latest',
    'region'  => 'your-region',
    'credentials' => [
        'key'    => 'your-access-key-id',
        'secret' => 'your-secret-access-key',
    ],
]);

Step 3: Upload a File to S3

Assuming you have a form allowing users to select a file, upon submission, that file must be moved to a temporary location on the server. Afterwards, use the S3 client to upload it to your S3 bucket.

$bucketName = 'your-bucket-name';
$keyName = basename($_FILES['userfile']['name']);
$filePath = $_FILES['userfile']['tmp_name'];

try {
    $result = $s3Client->putObject([
        'Bucket' => $bucketName,
        'Key'    => $keyName,
        'SourceFile' => $filePath, // also 'Body' => fopen($filePath, 'rb') can be used
        'ACL'    => 'public-read' // or 'private'
    ]);
    echo "File uploaded successfully. File URL:" . $result->get('ObjectURL');
} catch (S3Exception $e) {
    echo $e->getMessage();
}

Here, putObject method is used to upload the file. You can set the ACL (Access Control List) to public-read if you want the file to be publicly accessible, or you can keep it private.

Step 4: Handling Upload Errors

Errors can occur during the upload process, and it’s important to handle these gracefully. The S3Exception will be thrown if there’s any network error, invalid credentials, or if the file cannot be found.

Step 5: Additional Configuration

In addition to the basic file upload procedure, AWS S3’s putObject method allows for various configurations like setting metadata, tags, server-side encryption, etc.

$result = $s3Client->putObject([
    // ... previous code ...
    'Metadata' => [
        'CustomKey' => 'CustomValue'
    ],
    'Tagging' => 'key1=value1&key2=value2',
    'ServerSideEncryption' => 'AES256',
]);

Conclusion

In this guide, we walked through the steps of uploading a simple file to AWS S3 using PHP. This should form a good basis from which you can expand upon for more complex scenarios, such as handling larger files, direct browser uploads, and managing file versions on S3.

Additional Tips

  • For privacy-focused applications, use the private ACL setting.
  • If handling large files, consider using the multipart upload capability offered by AWS S3.
  • Remember, S3 is a pay-per-use service. Keep track of your usage to avoid unexpected charges.
  • Keep your AWS credentials secure by using environment variables or a credentials file.
  • Regularly update your AWS SDK to get the latest features and bug fixes.

With the knowledge from this tutorial, you can now integrate file storage into your PHP applications effortlessly using AWS S3’s robust cloud storage capabilities.