Upload Files to Amazon S3 using PHP
Wall Script
Follow Me:
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");
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


85 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. Very good tutorial Srinivas!

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

    ReplyDelete
  7. 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
  8. 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
  9. amazing tutorial, i just want to add this
    for Creating a bucket follow the link https://console.aws.amazon.com/s3/home

    thanks

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

    ReplyDelete
  11. how to create a bucket plz give reply

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

    ReplyDelete
  13. 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
  14. 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
  15. can we upload a video file into a folder using kohana frame work in php

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

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

    ReplyDelete
  18. 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
  19. Will this be a direct upload to the server, or moving it from temp directory to the server?

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

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

    ReplyDelete
  22. 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
  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?



    ReplyDelete
  24. "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
  25. 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
  26. 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
  27. Very Nice!!!

    Thanks for Shearing...

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

    ReplyDelete
  29. 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
  30. hi every one,

    i have also facing same above warning msg,

    plz help me

    ReplyDelete
  31. I think

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

    is a better way to get the file extension

    ReplyDelete
  32. 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
  33. 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
  34. this trick is really useful .. thanks many more ..

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

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

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

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

    ReplyDelete
  39. Is it possible free at Amazon ??

    ReplyDelete
  40. 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
  41. 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
  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. 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
  44. Amazing Tutorial it's working very Well..Thank you So Much..Srinivas Tamada...

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

    ReplyDelete
  46. 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
  47. 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
  48. help me .i want to upload image amezon s3 server same bucket but different folders.

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

    ReplyDelete
  50. 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
  51. i am using this code the problem is when i upload image it display the image upload fail.

    what is the reason..?

    ReplyDelete
  52. 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
  53. 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
  54. When I use this code and provide a static path to upload single file already exists in server, It'll work fine. But If I get paths from database, create a loop and upload them to s3, I am getting this Fatal error: Maximum execution time of 300 seconds exceeded in s3upload/S3.php on line 829.


    Can anyone suggest me any solution??

    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
  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

Make in India