AWS: Upload Folders/Files To S3 Bucket Using PHP
Using AWS S3 Bucket as a separate media storage platform definitely speeds up your application reducing the local server load. Especially, if your media files include audio/video and if the application offers the video streaming feature, using the general application server is not the best option as the performance, lag, server load, speed etc matter for both economical and user perspective success of the application.
In this article, I am gonna walk you through how you can implement the AWS S3 Bucket Storage feature using PHP. You will be able to programmatically make a request to store folders, files or objects into the bucket and ask for the data retrieval(depends on how you configure the permission/policy for public visibility) i.e. make a get request.
Now, Let’s dive into the tutorial.
How To Upload Folders/Files To AWS S3 Bucket Using PHP
The tutorial contains the following sections.
- Create A Bucket
- Create IAM User
- Setup Bucket Policy
- Setup CORS
- Setup User Policy
- Implement using PHP
Alright, Now we go through ease step at a time.
How to create a bucket in AWS S3 ?
- Open AWS Console and log in.
- Click the
Services
dropdown and select theS3
service. - Click
Create Bucket
. Give it a name, region then hit next through each step. - Now click your new bucket.
- Upload a test file manually to your bucket.
- You can find your new file. If you click it, you should see a link. If you open the link in a new tab, it will give you
AccessDenied
error.That’s because the default setting prevents public access to your bucket. We will get into this later for programmatic access. - We are done creating bucket.
How to create IAM User in AWS ?
- Click
Services
then go toIAM
dashboard. - You should see your
IAM
dashboard. On the left menu, you can clickUsers
. - Click the
Add User
. - Follow the steps accordingly and you will have brand new
IAM
user right away.
How to setup Bucket Policy for uploading files via PHP( programmatic access) ?
- Open S3 Dashboard.
- Select the bucket and click on it.
- Click on permissions tab.
- Scroll down to bucket policy and click edit.
- Paste the following into it. Change
arn:aws:iam::281979644754:user/sample-user
to be your User ARN. Also changearn:aws:s3:::sample-bucket
to your Bucket ARN.
{
"Version": "2012-10-17",
"Id": "Policy1488494182833",
"Statement": [
{
"Sid": "Stmt1488493308547",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::281979644754:user/sample-user"
},
"Action": [
"s3:GetObject",
"s3:GetObjectAcl",
"s3:putObject",
"s3:PutObjectAcl*",
],
"Resource": "arn:aws:s3:::sample-bucket"
}
]
}
How to setup CORS in AWS Bucket ?
- Open S3 Dashboard.
- Select the bucket and click on it.
- Click on permissions tab.
- Scroll down to CORS Configuration and click edit.
- Paste the following into it.
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST",
"HEAD",
"DELETE"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]
How to setup user policy for IAM User ?
- Open the
IAM
dashboard. - Open your user.
- Click on the
New inline policy
. - Update the policy to be as follows:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
],
"Resource": [
"arn:aws:s3:::*"
]
}
]
}
Now, since we have setup the aws properly for our programmatic file/folder uploads, let’s get into the programming part.
First of all, create a folder or a project in your web directory. If you are a linux user, create a folder in /var/www/html/
or if you use XAMPP
or LAMPP
, create folder in /directory-to-xampp-or-lampp/htdocs/
. I am gonna call it awsfileupload
.
Now, go to that folder and install aws sdk
using the following command. I am assuming you have composer
installed in your system.
composer require aws/aws-sdk-php
Once the sdk is installed, let’s create a file index.php
and upload.php
. We will be making a post request via form submission from index.php
and the actual file upload operation will happen in upload.php
.
Paste the following into your index.php
. It only contains a simple form for demonstration. You can modify however you like.
<html>
<head>
<title>AWS File Upload</title>
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
Now, paste the following into your upload.php
file.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'your-bucket-name';
$IAM_KEY = 'your-iam-key';
$IAM_SECRET = 'your-iam-secret';
$REGION = 'your-bucket-region';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => $REGION
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
$keyName = 'my_folder/' . basename($_FILES["file"]['name']);
$pathInS3 = 'https://s3.'.$REGION.'.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["file"]['tmp_name'];
$result = $s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
$url = $result['ObjectURL'];
echo 'File Uploaded Successfully !'.$url;
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
?>
Now, save the files and open the url of your folder/project. In my case, it would be http://localhost/awsfileupload
. It will give you a simple form to select a file and click on upload. The file should get uploaded. You will see the message File Uploaded Successfully ! https://url-to-your-bucket-file .You can check if its true by visiting your bucket and verifying the objects present there.
Hope you enjoyed the tutorial. Feel free to leave a comment.