Upload Files to Amazon S3 using PHP
Wall Script
Wall Script
Tuesday, August 07, 2012

Upload Files to Amazon S3 using PHP

Are you looking for Amazon S3 bucket file upload from your web project using PHP technology, if yes take a quick look at this post demo. Amazon S3 is the best option to reduce the bandwidth cost as well file load time. Upload functionality is the most sensitive part in web project, one small mistake hackers will upload miscellaneous files. If you are connect with Amazon S3 you will be safe side.

Upload Files to Amazon S3 PHP

Download Script     Live Demo

Download script contains four files.
S3.php //Amazon S3 library file
s3_config.php //Key configuration file
image_check.php //File validator
index.php

Login to Amazon account and click here to get Access Credentials.
Upload Files to Amazon S3 PHP

s3_config.php
Here you have to provide amazon key details.
<?php
// Bucket Name
$bucket="BucketName";
if (!class_exists('S3'))require_once('S3.php');

//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'ACCESS_KEY');
if (!defined('awsSecretKey')) define('awsSecretKey', 'ACCESS_Secret_KEY');

$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);
?>

index.php
The file contains PHP and HTML code to submit form.
<?php
include('image_check.php'); // getExtension Method
$msg='';
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$tmp = $_FILES['file']['tmp_name'];
$ext = getExtension($name);

if(strlen($name) > 0)
{
// File format validation
if(in_array($ext,$valid_formats))
{
// File size validation
if($size<(1024*1024))
{
include('s3_config.php');
//Rename image name.
$actual_image_name = time().".".$ext;

if($s3->putObjectFile($tmp, $bucket , $actual_image_name, S3::ACL_PUBLIC_READ) )
{
$msg = "S3 Upload Successful.";
$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
echo "<img src='$s3file'/>";
echo 'S3 File URL:'.$s3file;
}
else
$msg = "S3 Upload Fail.";

}
else
$msg = "Image size Max 1 MB";

}
else
$msg = "Invalid file, please upload image file.";

}
else
$msg = "Please select image file.";

}
?>

//HTML Code
<form action="" method='post' enctype="multipart/form-data">
Upload image file here
<input type='file' name='file'/> <input type='submit' value='Upload Image'/>
<?php echo $msg; ?>
</form>

Create a bucket and right click select properties, add permission select Everyone enable check list box.
Upload Files to Amazon S3 PHP

image_check.php
This file help you to get file extension.
<?php
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//Here you can add valid file extensions. 
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
?>
web notification

96 comments:

  1. Yet another useful tutorial, I'm looking for multiple file uploader, will that be possible ?

    ReplyDelete
  2. Can you share same like script for ebay?????

    ReplyDelete
  3. Nice Work. Selecting multiple files at once?

    ReplyDelete
  4. awesome awesome aswesome

    ReplyDelete
  5. Any way to do this with media files?

    ReplyDelete
  6. How would you tweek this so you can upload files that aren't just basic image files, like PDFs, or Zip files?
    Thank you for any help....

    ReplyDelete
  7. I would like to upload mp3 files. I changed the code, but every time I try to upload mp3 file, script returns 'S3 Upload Fail'

    ReplyDelete
  8. amazing tutorial, i just want to add this
    for Creating a bucket follow the link https://console.aws.amazon.com/s3/home

    thanks

    ReplyDelete
  9. showing file upload progress would make this tutorial perfect

    ReplyDelete
  10. how to create a bucket plz give reply

    ReplyDelete
  11. @siddhu vydyas you can use a firefox extension called s3 organizer. and you can create a bucket.

    ReplyDelete
  12. Great job done here, many thanks for this code, I had no idea this is possible at all. And I also would like to say that you have a very informative blog in general, keep it up this way!

    ReplyDelete
  13. Thanks for the code. Can i upload any video and audio files with mp3,mp4 extensions and if i can do can u please let me know where the code has to be changed and what has to be changed ?

    ReplyDelete
  14. can we upload a video file into a folder using kohana frame work in php

    ReplyDelete
  15. It's possible to add progress bar ?. I'm stuck with this. Thanks :-)

    ReplyDelete
  16. What should be the setting if one is not using the default us data center?

    ReplyDelete
  17. Thanks,very nice post. Append folder name to $actual_image_name then it will put the file to FOLDER.

    ReplyDelete
    Replies
    1. $actual_image_names='music/aaha_music_file/mood/tense/'.$actual_image_name;
      use this line in your code this is my folder structure

      Delete
  18. Will this be a direct upload to the server, or moving it from temp directory to the server?

    ReplyDelete
  19. Great job, my only work is to rename the folder

    ReplyDelete
  20. Will this be a direct upload to the server, or moving it from temp directory to the server?

    ReplyDelete
  21. In my bucket I have a folder, I want to upload the file to the specific folder within my bucket, how can I do that?

    ReplyDelete
  22. In shared hosts running Apache + PHP, the maximum file size to upload will be fixed by 'post_max_size' or this rule will be bypassed?



    ReplyDelete
  23. "In shared hosts running Apache + PHP, the maximum file size to upload will be fixed by 'post_max_size' or this rule will be bypassed?"

    Looks like s3 is not even called for until the file size is checked. This means you should be limited to the php.ini max size. Fill me in if I'm wrong.

    ReplyDelete
  24. Very Nice Tutorial,

    I am using this exemplo to upload my images.

    I have only a littler question:

    I am try to send to S3 some resize images. I send the original photo and after I need to resize this image and send to S3 the resized images.

    How can I resize a image and send to S3?

    ReplyDelete
  25. Good night Srinivas Tamada. You have a great article and very informative website. But with this script, I have a problem. The fact is that I have no way to change the time zone on the server. what to do in such cases, how to deal with the problem?. I will be glad to hear what you think about it.

    P.S. Sorry for my bad English

    ReplyDelete
  26. Very Nice!!!

    Thanks for Shearing...

    ReplyDelete
  27. How do I set the storage type to 'reduced redundancy'?

    ReplyDelete
  28. Hi,
    I've a problem with the script: AWSn send an error message:
    Warning: S3::putBucket(asfilms): [SignatureDoesNotMatch] The request signature we calculated does not match the signature you provided. Check your key and signing method. in /data/web/e23531/html/foto-news.tv/upload/S3.php on line 188

    Warning: S3::putObject(): [SignatureDoesNotMatch] The request signature we calculated does not match the signature you provided. Check your key and signing method. in /data/web/e23531/html/foto-news.tv/upload/S3.php on line 312

    What does it meens?

    BEst regads
    Achim

    ReplyDelete
  29. hi every one,

    i have also facing same above warning msg,

    plz help me

    ReplyDelete
  30. I think

    $file_parts = pathinfo('image_name.ext');
    $ext = $file_parts ['extension'];

    is a better way to get the file extension

    ReplyDelete
  31. Hi, I think time() is not the best way to rename the file, as it returns the current time in seconds, so what if multiple users at the same second of time upload images, won't it create some troubles ? Or Amazon renames them as well? Than I guess it won't be problem
    Thanks

    ReplyDelete
  32. I'm with Chris for the use of `pathinfo()` function.

    Also instead of listing both the lowercase and uppercase valid extensions you could just do this:

    $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
    $valid_ext = in_array(strtolower($ext), $valid_formats);

    ReplyDelete
  33. this trick is really useful .. thanks many more ..

    ReplyDelete
  34. Thanks Srinivas,
    But in my case, how i can write api upload file to S3 for mobile?

    ReplyDelete
  35. Please let me know , How to store media in REDUCED_REDUNDANCY format.
    Thanks in Advance .

    ReplyDelete
  36. very useful tool - How to upload a file to a subfolder?

    ReplyDelete
  37. Helllo dude Amazon S3 buket is free ... na ???

    ReplyDelete
  38. Is it possible free at Amazon ??

    ReplyDelete
  39. Hello,
    I am getting the below warnings and I am not able to upload the images to the bucket.

    Warning: S3::putBucket(ideacarvetest): [BucketAlreadyOwnedByYou] Your previous request to create the named bucket succeeded and you already own it. in C:\xampp\htdocs\s3upload\S3.php on line 188

    Warning: S3::putObject(): [TemporaryRedirect] Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests. in C:\xampp\htdocs\s3upload\S3.php on line 312


    Kindly Look into it.

    Thanks in Advance.

    Regards,
    Pavan

    ReplyDelete
  40. I never found a updated Script with Amazons latest sdk. i have made it by myself. it woks as a php commandline interpreter script. give it a try : https://github.com/arizawan/aiss3clientphp

    ReplyDelete
  41. Awesome work thanks for sharing

    ReplyDelete
  42. that was an awesome work.I would like to know one more thing.I am using S3 buckets to store my images and I need to fetch these images to my local machine and compress these images and then upload to CDN's.This works good.But when I had enabled a load balancer its not working.Any idea why this happens?

    ReplyDelete
  43. thanks brother....

    ReplyDelete
  44. Hai ...Thanks For Your Code.....But Can You Please Help in in uploading the image fetching from one server(using path directory,else link), this image has to be uploaded to Amazon S3 Bucket

    Thanks In Advance...!!

    ReplyDelete
  45. Amazing Tutorial it's working very Well..Thank you So Much..Srinivas Tamada...

    ReplyDelete
  46. is it safe for wordpress, joomla sms plugins?

    ReplyDelete
  47. Notice: Undefined property: stdClass::$body in E:\Xampp\htdocs\s3\S3.php on line 877

    Warning: S3::putBucket(webserviceimage): [BucketAlreadyOwnedByYou] Your previous request to create the named bucket succeeded and you already own it. in E:\Xampp\htdocs\s3\S3.php on line 188

    Notice: Undefined property: stdClass::$body in E:\Xampp\htdocs\s3\S3.php on line 877

    Warning: S3::putObject(): [TemporaryRedirect] Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests. in E:\Xampp\htdocs\s3\S3.php on line 312

    ReplyDelete
  48. i want to move file's from one directory to another directory on same bucket in aws s3 server.
    if you have any solution please giive me solution for this

    ReplyDelete
  49. help me .i want to upload image amezon s3 server same bucket but different folders.

    ReplyDelete
  50. how to display pdf in amazon s3 without download option in website

    ReplyDelete
  51. Undefined property: stdClass::$body [APP/Vendor/s3upload/S3.php, line 884]

    S3::putBucket(pfyi): [BucketAlreadyOwnedByYou] Your previous request to create the named bucket succeeded and you already own it. [APP/Vendor/s3upload/S3.php, line 189]

    help me please..

    ReplyDelete
  52. i am using this code the problem is when i upload image it display the image upload fail.

    what is the reason..?

    ReplyDelete
  53. Thanks for sharing!
    It's working fine but I need help that If we make that private then how we can access image.
    Please can you please help me out of this.

    Thanks
    Ashish

    ReplyDelete
  54. It's working fine..my problem ..am unable to sent email with attachment in EC2 instances ..i try move the file from s3 to ec2 ..but i can't due to some reason...

    ReplyDelete
  55. Deployed it to Heroku. Really cool! This is great.

    ReplyDelete
  56. Thank u very much , made my job easy

    ReplyDelete
  57. thank you very much but I need your help upload home market very well possible to download the script depuid Amazon S3 please thank you in advance

    ReplyDelete
  58. hi, i am trying this from last 2 days but its give error again and again whenever i try to upload file. errors are : access denied line 188 or line 312 in s3_config.php.

    please help me

    ReplyDelete
  59. hi . i am trying this amazon form last 2 days but i got error again and again whenever it try to upload kindly help me . error was .. ACCESS DENIED ON S3_CONFIG.PHP line 188 or line 312 .

    regards

    ReplyDelete
    Replies
    1. I got the same problem. What should i do now?

      Delete
  60. I also keep getting the S3 Upload Fail. Is there something I'm missing? Help is much appreciated!

    ReplyDelete
  61. Awesome tutorial!!

    Having question here. Can we get request URL like with extension .m3u8 and .hls from s3 bucket ?

    ReplyDelete
    Replies
    1. Add file extensions here.

      $valid_formats =
      array("jpg","png","gif","bmp","jpeg","m3u8",
      "hls","PNG","JPG","JPEG","GIF","BMP");

      Delete
  62. Can any one please advise how to upload image in subfolder inside a bucket?

    ReplyDelete

  63. Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 877

    Warning: S3::putBucket(appiness-1234): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 188

    Notice: Use of undefined constant console - assumed 'console' in D:\xampp\htdocs\s3upload\index.php on line 22

    Warning: log() expects parameter 1 to be double, string given in D:\xampp\htdocs\s3upload\index.php on line 22

    Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 877

    Warning: S3::putObject(): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 312

    ReplyDelete
  64. Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 852

    Warning: S3::putBucket(appiness-1234): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 163

    Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 852

    Warning: S3::putObject(): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 287

    ReplyDelete
  65. Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 851

    Warning: S3::putBucket(appiness-1234): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 162

    Notice: Undefined property: stdClass::$body in D:\xampp\htdocs\s3upload\S3.php on line 851

    Warning: S3::putObject(): [InvalidArgument] Authorization header is invalid -- one and only one ' ' (space) required in D:\xampp\htdocs\s3upload\S3.php on line 286


    S3 Upload Fail

    ReplyDelete
  66. Hello I m testing this code with my Local machine. I have accesKey,Secret Key.But this is not working. I putt bucketname"local".This shows3 Upload Faail

    ReplyDelete
    Replies
    1. Bucketname name should be valid one, try to create in Amazon S3

      Delete
  67. hello i used this program for upload file in amazon server. my file upload correctly.but i got two errors.

    Notice: Undefined property: stdClass::$body in C:\xampp\htdocs\server_upload\s3upload\S3.php on line 877

    Warning: S3::putBucket(pipline): [BucketAlreadyOwnedByYou] Your previous request to create the named bucket succeeded and you already own it. in C:\xampp\htdocs\server_upload\s3upload\S3.php on line 188

    please solve this error ASAP.

    ReplyDelete
  68. HI Srinivas,
    Can you let me know how to upload image in folder inside a bucket?

    ReplyDelete
  69. I'm getting this error in error logs:

    PHP message: PHP Warning: S3::putObject(): [TemporaryRedirect] Please re-send this request to the specified temporary endpoint. Continue to use the original request endpoint for future requests. in /usr/share/nginx/html/includes/S3.php on line 312" while reading response header from upstream, client: 182.73.91.19, server: portal.happyme.net, request: "POST /x/upload.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm/php-fpm.sock:", ......

    Its been a couple of hours since I create the bucket.

    Any suggestions?

    ReplyDelete
  70. upload .csv & .xls files getting error

    Notice: Undefined property: stdClass::$body in C:\xampp\htdocs\abc\S3.php on line 877

    Warning: S3::putObject(): [HttpVersionNotSupported] The HTTP version specified is not supported. in C:\xampp\htdocs\abc\S3.php on line 312

    Any suggestions?

    ReplyDelete
  71. It works with default region, but if the region = us-west-2, then how to include it within the code?

    ReplyDelete
  72. Hi Srinivas,
    This upload functionality works with default region, but if the region = us-west-2, how do I include it in the code? For now I'm experiencing "S3 Upload Fail" as I couldn't include region in your code.
    Plz advice.

    Thanks in advance.

    ReplyDelete
  73. Hi sir,

    i am work on local machine. with region=us-west-2

    i got below error.

    So please help me ASAP.


    Notice: Undefined property: stdClass::$body in F:\xampp\htdocs\aws\S3.php on line 877

    Warning: S3::putBucket(magics3bucket): [InvalidRequest] The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. in F:\xampp\htdocs\aws\S3.php on line 188

    Notice: Undefined property: stdClass::$body in F:\xampp\htdocs\aws\S3.php on line 877

    Warning: S3::putObject(): [InvalidRequest] The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. in F:\xampp\htdocs\aws\S3.php on line 312

    ReplyDelete
    Replies
    1. Hey, I get the same error!
      This code used to work with my old bucket. the new one fails.
      Did you manage to fix this or any other solution?

      Delete
  74. Hi,
    not getting response from s3 when try to upload above 2mb size images taken from ipad or iphone 6

    ReplyDelete
  75. can i upload images to AWS S3 from localhost for testing purpose,
    please please please tell mee

    ReplyDelete
  76. Warning: S3::getBucket(): [InvalidRequest] The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

    ReplyDelete
    Replies
    1. Hey Ajay, I get the same error!
      This code used to work with my old bucket. the new one fails.
      Did you manage to fix this or any other solution?

      Delete
  77. Warning: S3::putBucket(sadique-videos, public-read, ): [InvalidRequest] The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. in C:\wamp64\www\amazon\S3.php on line 374

    Iam getting above error

    ReplyDelete
  78. Can you PLease tell me how can I customize this code to store the file in bucket folder

    ReplyDelete

mailxengine Youtueb channel
Make in India
X