Introduction

This guide explains how to create a simple PHP-based web application that uploads files to an Amazon S3 bucket using the AWS SDK for PHP. The application allows users to select a file through a web interface, temporarily stores it on the server, uploads it to the specified S3 bucket, and then removes the local copy after a successful upload.

The script is intended for basic file upload requirements and can be easily integrated into existing PHP applications. Before using this solution, ensure that your web server supports PHP, Composer is installed, and valid AWS IAM credentials with S3 upload permissions are available.

Prerequisites:

  1. Webserver which support to run php application
  2. Composer installed on the host.
  3. AWS access & secret key to upload file.
  4. File Size should not be more than 1MB.

Script Setup:

Install aws-sdk on the domain document Root

composer require aws/aws-sdk-php

If Composer is not installed, use the following command to install Composer.

curl -sS https://getcomposer.org/installer | php

Copy the following script and upload it to the document root directory. Replace all the bolded lines with Appropriate values
<!-- Php

File to upload image to s3 Bucket
Author: Dhanasekaran N
Email:support@pheonixsolutions.com
Next time even Bigger with more. Love to do it in PHP
Version:0.1
-->
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
ini_set('display_errors', 1);
if(isset($_POST['upload']))
{
$target_dir="/tmp/s3upload/";
$mode=0777;
echo "Worray. Its working.....";
$filename=$_FILES['s3file']['name'];
$filesize=$_FILES['s3file']['size'];
echo $fileextension=pathinfo($filename, PATHINFO_EXTENSION);
echo $target_file=$target_dir.$filename;
if(strlen($filename) > 0)
{
if($filesize<(1024*1024))
{
#echo "File is less than 1MB. Let's Upload...";
if(!is_dir($target_dir))
{
mkdir($target_dir,$mode, true);
}
//move_uploaded_file($_FILES['s3file']['name'], $target_file);
if(move_uploaded_file($_FILES['s3file']['tmp_name'], $target_file))
{
#echo "Local Uploaded Successfully";
echo $target_file;
echo "Lets put the object to s3...";
$bucket="<BUCKET-NAME>";
$client = new Aws\S3\S3Client([
'version' => 'latest',
'region' => '<Region>',
'credentials' => [
‘key’ => ‘XXXXXX’, # <- Put your Aws Access Key
‘secret’ => ‘xxxxxxx' #<- Put your Secret Key
]
]);
try
{
echo "Trying upload to s3";
$client->putObject(array(
'Bucket'=>$bucket,
'Key' => '<PATH To UPLOAD>'.$filename, # <- PATH to Upload. Eg.,Directory/Subdirectory1
'SourceFile' => $target_file,
));
$message = "S3 Upload Successful.";
echo $message;
echo "<script> alert('File Uploaded Successfully')</script>";
#echo "Delete the temporary file.";
unlink($target_file);
}
catch (S3Exception $e) {
// Catch an S3 specific exception.
echo $e->getMessage();
}
}
else
{
echo "Upload Failed";
}

}
else
{
echo "File is greater than 1MB";
}
}
else
{
echo "Please Select the file";
}

}
?>

<html>
<head>
<title>Pheonix solutions S3 Image upload </title>
<style type="text/css">
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
body {
background-color: lightgrey;
}
h1 {
color: navy;
margin-left: 20px;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.btn-success,
.btn-green {
color: #ffffff;
background-color: #00a651;
border-color: #00a651;
}

.btn-file {
overflow: hidden;
position: relative;
vertical-align: middle;
}
.fileinput-exists .fileinput-new, .fileinput-new .fileinput-exists {
display: none;
}
.fileinput .thumbnail {
overflow: hidden;
display: inline-block;
margin-bottom: 5px;
vertical-align: middle;
text-align: center;
}
.panel-primary {
border-color: #ebebeb;
-webkit-border-radius: 3px;
-webkit-background-clip: padding-box;
-moz-border-radius: 3px;
-moz-background-clip: padding;
border-radius: 3px;
background-clip: padding-box;
}

body {
font-family: "Helvetica Neue", Helvetica, "Noto Sans", sans-serif, Arial, sans-serif;
font-size: 12px;
line-height: 1.42857143;
color: #949494;
background-color: lightgrey;
}
</style>
</head>
<body>
<form action="" method='post' enctype="multipart/form-data">
<h1><center>Image Upload DashBoard! Build by Pheonix Solutions</center></h1>
<div class="main-content">
<div class="panel panel-primary ">
<label> Please Select the image to upload</label><br>
<input type='file' class="fileinput thumbnail btn btn-file" name='s3file'/> <br>
</div>
<input type='submit' class="btn btn-success" name='upload' value='Upload Image'/>
</div>

</body>
</html>

 

Conclusion

By following this guide, you can quickly implement a secure and efficient file upload mechanism from a PHP web application to an Amazon S3 bucket. The script demonstrates the complete workflow, including file validation, temporary local storage, S3 upload using the AWS SDK, error handling, and cleanup of temporary files.

For production environments, it is recommended to enhance the script by implementing additional security measures such as validating file MIME types, restricting allowed file extensions, securely storing AWS credentials (using IAM roles or environment variables instead of hardcoding them), increasing logging, and supporting larger file uploads through multipart upload if required. These improvements will help ensure better security, scalability, and maintainability of your application.

Leave a Reply