Introduction
Amazon S3 is a scalable object storage service that can be used to store and manage files securely. This guide explains how to create a simple PHP-based file upload application that uploads a file to an Amazon S3 bucket using the AWS SDK for PHP. The script first stores the uploaded file temporarily on the server and then transfers it to the specified S3 bucket.
Prerequisites
Before proceeding, make sure you have:
- A web server capable of running PHP applications.
- Composer installed on the server.
- AWS access credentials with appropriate permissions to upload objects to the S3 bucket.
- An existing S3 bucket and the required AWS Region.
- The uploaded file size must be less than 1 MB.
- The PHP application must have permission to create and write to the temporary upload directory.
Implementation
Script Setup:
Install aws-sdk in 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 BucketAuthor: Dhanasekaran NEmail:support@pheonixsolutions.comNext time even Bigger with more. Love to do it in PHPVersion:0.1--><?phprequire '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-NAME> $bucket=""; $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,<PATH To UPLOAD> 'Key' => ''.$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
Using the AWS SDK for PHP provides a simple way to upload files from a PHP application directly to an Amazon S3 bucket. The script temporarily stores the uploaded file on the server, uploads it to the specified S3 location, and removes the temporary file after a successful upload. For production environments, avoid hardcoding AWS access keys in the PHP script and use IAM roles, environment variables, or another secure credential mechanism.
FAQs
1. What is the maximum file size supported by this script?
The script allows files smaller than 1 MB. Files larger than 1 MB are rejected.
2. Why is Composer required for this script?
Composer is used to install and manage the AWS SDK for PHP, which provides the required S3 functionality.
3. Can AWS access keys be hardcoded in the PHP script?
Although the script demonstrates access and secret keys directly in the configuration, hardcoding credentials is not recommended for production. Use IAM roles, environment variables, or another secure credential-management method instead.
Related Articles
Automate MySQLdump Backup from server(backend) to Amazon S3
Talk to our experts
Looking for the right technology solution for your business?. Our experts can help with web hosting, domain registration, DevOps and cloud, software development, web applications, mobile applications, and enterprise solutions. Get in touch with our team here.