Upload Files to Amazon S3 Bucket using PHP
Amazon S3 (Simple Storage Service) is a storage service provided by Amazon Web Services (AWS). Amazon S3 is highly scalable data storage to store and retrieve data over the internet. When a web application dealt with a huge number of files, a separate storage service can be used to reduce the bandwidth usage of the application server. Amazon S3 is the best option to store files separately from the application server and helps to reduce the file load time. If web applications allow users to upload files in PHP, generally the files are stored on the local server. You can upload and store files to AWS S3 instead of the local server. The process is very simple to upload, store, and retrieve files from Amazon S3 bucket with PHP SDK. In this tutorial, we will show you how to upload files to Amazon S3 bucket using PHP.
Before getting started, you need to create an AWS account and login to the AWS Management Console.
- Search for the S3 service and go to the S3 Management Console.
Create S3 Bucket:
In AWS S3, the buckets are like a container that holds files in data storage. You need to create a bucket to upload files in Amazon S3.
Get Access Key ID and Secret Access Key from AWS Account:
- Go to the IAM Console.
- From the left navigation menu, select Users under the Access management section.
- Create a user with AmazonS3FullAccess permission.
- On success, the Access Key ID and Secret Access Key will be generated. Note these AWS credentials to use in the code later.
Install AWS SDK for PHP
We will use the AWS SDK library to upload files to AWS S3 bucket using PHP.
You can use Composer to install AWS SDK in the script folder. Run the following command on the terminal to install AWS PHP SDK with Composer.
composer require aws/aws-sdk-php
Alternatively, you can use our source code to install AWS SDK without composer.
Note that: All the required files including the AWS SDK PHP library are included in our source code, you do not require to install AWS SDK separately.
Create File Upload Form
Define HTML elements to build an upload form with a file input field and submit button. Make sure the <form> tag contains the following attributes.
method="post"
enctype="multipart/form-data"
<form method="post" action="" enctype="multipart/form-data">
<div class="form-group">
<label><b>Select File:</b></label>
<input type="file" name="userfile" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="Upload">
</div>
</form>
Upload File to Amazon S3
The following code handle the Amazon S3 file upload operations with AWS SDK using PHP.
- Load the autoloader file and use the
S3Client
namespace from AWS SDK. - Specify the Amazon S3 API credentials which will get from your AWS S3 account console.
- Use PHP is_uploaded_file() function to check whether the selected file is uploaded to the temp path in the local server.
- Instantiate an Amazon S3 client using
S3Client()
class and pass the configuration options (version, region, credentials.key, and credentials.secret). - Upload file to S3 bucket using
putObject()
method of the S3Client.- Bucket – S3 bucket name.
- Key – Name of the file.
- ACL – Set
public-read
to make the uploaded file publicly accessible. - SourceFile – Specify the temp path of the file.
- In the S3Client response, we will get the S3 bucket file URL in the ObjectURL key.
- This
ObjectURL
can be used to access the uploaded file from the Amazon S3 bucket on the web page.
- This
PHP Code to Upload File to Amazon S3
<?php
// Include the AWS SDK autoloader
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Amazon S3 API credentials
$region = 'AWS_REGION';
$version = 'latest';
$access_key_id = 'AWS_ACCESS_KEY';
$secret_access_key = 'AWS_SECRET_KEY';
$bucket = 'S3_BUCKET_NAME';
$statusMsg = '';
$status = 'danger';
// If file upload form is submitted
if(isset($_POST["submit"])){
// Check whether user inputs are empty
if(!empty($_FILES["userfile"]["name"])) {
// File info
$file_name = basename($_FILES["userfile"]["name"]);
$file_type = pathinfo($file_name, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf','doc','docx','xls','xlsx','jpg','png','jpeg','gif');
if(in_array($file_type, $allowTypes)){
// File temp source
$file_temp_src = $_FILES["userfile"]["tmp_name"];
if(is_uploaded_file($file_temp_src)){
// Instantiate an Amazon S3 client
$s3 = new S3Client([
'version' => $version,
'region' => $region,
'credentials' => [
'key' => $access_key_id,
'secret' => $secret_access_key,
]
]);
// Upload file to S3 bucket
try {
$result = $s3->putObject([
'Bucket' => $bucket,
'Key' => $file_name,
'ACL' => 'public-read',
'SourceFile' => $file_temp_src
]);
$result_arr = $result->toArray();
if(!empty($result_arr['ObjectURL'])) {
$s3_file_link = $result_arr['ObjectURL'];
} else {
$api_error = 'Upload Failed! S3 Object URL not found.';
}
} catch (Aws\S3\Exception\S3Exception $e) {
$api_error = $e->getMessage();
}
if(empty($api_error)){
$status = 'success';
$statusMsg = "File was uploaded to the S3 bucket successfully!";
}else{
$statusMsg = $api_error;
}
}else{
$statusMsg = "File upload failed!";
}
}else{
$statusMsg = 'Sorry, only Word/Excel/Image files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
?>
Conclusion
Here, we develop a simple script to upload files and store files in Amazon S3 bucket programmatically using PHP. You can use this example script in the website to allow the user to upload files and host them on Amazon Simple Storage Service (S3). Amazon S3 file upload functionality is very useful when you want to reduce the usage of the application server space and access the user-uploaded files faster on the web page.
What's Your Reaction?