Upload Files To Amazon S3 Using AWS PHP SDK

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

Amazon S3 provides a high-scalable object storage. As it comes under a brand name Amazon, obviously S3 is a popular cloud service among the people. Other popular cloud platforms are Google Cloud, Microsoft Azure, Rackspace.

Why Need To Upload Files On Amazon S3?

Well, there are several reasons behind this. By uploading your files to a cloud you can have access to them from anywhere. AWS provides you a cool feature to keep your document either public or private. Second thing is, if you are running a website then keeping your images in the cloud will save you a lot of bandwidth. It saves your hosting space.

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

Get Your Security Credentials

To get started with S3, you should first have account on Amazon S3. After creating the account make sure you have activated the service S3 by following their verification process.

Once you activated the S3 service, get your security credentials which we will need while working with the APIs.

Go to credentials

Actual Code For Uploading Files To Amazon S3

Now we have our API keys ready with us. Next thing to do is install an official AWS PHP SDK library of Amazon.

We recommend to use Composer to install this GitHub library.

Open the terminal in your project root directory and run the below command.

composer require aws/aws-sdk-php

It will install the library with their dependencies into your project.

Create A Bucket On AWS

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

For creating the Bucket, we need to write following piece of code. Let’s create a file create-bucket.php file.

create-bucket.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',
    ]);
} 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 AWS profile. We will upload the file to this Bucket through the API. In the above code we passed key=>value pair 'ACL' => 'public-read'. This pair makes your Bucket or files public. If you wish to keep your storage private then remove this line from the code.

For the sake of our tutorial, we are creating different PHP files and writing a code in it. In your case, feel free to implement the logic depends on your project flow.

Upload File To Bucket

Next, create a file upload-to-aws.php and place the below code in the file.

upload-to-aws.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 $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
    echo "There was an error uploading the file.\n";
    echo $e->getMessage();
}

Here, we need to pass the name of Bucket in which we wish to store the file. In our case, we consider to upload file my-image.png, so we passed directory path of the image. You should adjust your path to the image. To get the AWS path of an uploaded file we need to call get() method on the response result given by S3.

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

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

Posted in PHP

Leave a Reply

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