Upload Files to Amazon S3 Using AWS PHP SDK

Do you want to upload files to Amazon S3 programmatically? Amazon S3 is a cloud storage service where one can store files, images, etc. These documents can be public or private depending on the owner’s choice. In this article, we study how to upload files to Amazon S3 using the official AWS PHP SDK library.

Amazon S3 provides high-scalable object storage. Because of its robustness and performance, it is a popular cloud service among users.

Why Need to Upload Files On Amazon S3?

Well, there are several reasons to keep your files on Amazon S3. As it’s a cloud-based service, you can access your files from anywhere. While using this service, users can keep their documents confidential. AWS provides you a feature to keep your document either public or private. Secondly, if you are running a website then keeping your files on the cloud will save you a lot of bandwidth. It saves your hosting space and reduces the loads on your server.

That being said, let’s take a look at how to upload files on Amazon S3 using PHP.

Get Your Security Credentials

To get started with S3, you should have an account on AWS. After creating the AWS account make sure to activate the service S3 by following their verification process.

Upon activating the S3 service, get your security credentials which we will require while working with the APIs.

Go to credentials

Code for Uploading Files to Amazon S3

We are ready with AWS API keys. Next, install an official AWS PHP SDK library into your project. I recommend to use Composer to install this library. Open the terminal in your project root directory and run the below command.

composer require aws/aws-sdk-php

This command will install the library with their dependencies into your project.

Create a Bucket On AWS

In AWS, we need to create a Bucket to store our files. The bucket is nothing but a logical unit of storage in AWS. All your files will be stored inside the bucket.

You can create a bucket on the S3 dashboard directly. But if someone is looking to create it dynamically then refer to the code below.

create-bucket.php

<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;

$bucketName = 'YOUR_BUCKET_NAME';

$client = new S3Client([
    'version' => 'latest',
    'region' => 'YOUR_AWS_REGION',
    'credentials' => [
        'key'    => 'ACCESS_KEY_ID',
        'secret' => 'SECRET_ACCESS_KEY'
    ]
]);

try {
    $result = $client->createBucket([
        'Bucket' => $bucketName, // REQUIRED
        'ACL'    => 'public-read',
    ]);
    echo "Bucket created successfully.";
} catch (Aws\S3\Exception\S3Exception $e) {
    // output error message if fails
    echo $e->getMessage();
}

Make sure to replace the placeholders with the actual values. This code creates a bucket on your S3 dashboard. We will upload the files under this bucket through the API.

In the above code I passed key=>value pair as 'ACL' => 'public-read'. This pair sets your bucket or files access to the public. If you wish to keep your storage private then remove this line from the code.

The next job is writing code for uploading files on Amazon S3. For the sake of the tutorial, I am creating different PHP files and writing code in it. In your case, feel free to implement the logic depending on your project flow.

Upload File to Amazon S3

You are ready with the bucket to store your files. Create a file upload-to-s3.php and place the below code in this file.

upload-to-s3.php

<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'YOUR_AWS_REGION',
    'credentials' => [
        'key'    => 'ACCESS_KEY_ID',
        'secret' => 'SECRET_ACCESS_KEY'
    ]
]);


$bucketName = 'YOUR_BUCKET_NAME';
$file_Path = __DIR__ . '/my-image.png';
$key = basename($file_Path);

// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
    $result = $s3->putObject([
        'Bucket' => $bucketName,
        'Key'    => $key,
        'Body'   => fopen($file_Path, 'r'),
        'ACL'    => 'public-read',
    ]);
    echo "Image uploaded successfully. Image path is: ". $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
    echo $e->getMessage();
}

Here, you should assign the name of bucket for $bucketName variable. In my case, I am uploading a file say ‘my-image.png’ which path I set in the code. Accordingly, you should adjust the path of your files. Finally, I am printing the path of an uploaded file using get() method on the response received.

All done! Now run the upload-to-s3.php file on the browser and your file should be uploaded on Amazon S3 bucket.

I hope you understand about creating a bucket and uploading files to Amazon S3. You may also want to check example codes provided by AWS on GitHub.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “Upload Files to Amazon S3 Using AWS PHP SDK

    1. What was the error? Is it related to maximum execution time exceeded? If so, you need to edit the PHP configuration file and increase the execution time.

      Alternately, add the below line to the code which will removes the execution time limit.

      set_time_limit(0);

  1. Fantastic!! Fully working code. But not mentioned about bucket policy. Without appropriate bucket policy the code will not work.

Leave a Reply

Your email address will not be published. Required fields are marked *