February 21, 2024 5:02 am

How to Upload multiple images jQuery Ajax using PHP

I have received many requests from my readers to on how to upload multiple images in jQuery and PHP, so this is the article which I have wrote and explain jQuery and PHP to upload multiple images at once. You can use this as a reference for your web projects, specially focused on newbies to understand the procedures of images uploading.

How to Upload multiple images jQuery Ajax using PHP

[wpdm_file id=59]DEMO

Used a jQuery Library from hayageek.com and create tutorial in more simple way.

We also publish two tutorials on image upload

  1. File uploading with PHP
  2. How to Upload Image using jQuery with progress in PHP

Here is index.html file which contain jQuery library and CSS to handle your requests.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/uploadfilemulti.css" rel="stylesheet">
<script src="js/jquery-1.8.0.min.js"></script>
<script src="js/jquery.fileuploadmulti.min.js"></script>
</head>
<body>

<div id="mulitplefileuploader">Upload</div>

<div id="status"></div>
<script>

$(document).ready(function()
{

var settings = {
	url: "upload.php",
	method: "POST",
	allowedTypes:"jpg,png,gif,doc,pdf,zip",
	fileName: "myfile",
	multiple: true,
	onSuccess:function(files,data,xhr)
	{
		$("#status").html("<font color='green'>Upload is success</font>");
        },
        afterUploadAll:function()
        {
                alert("all images uploaded!!");
        },
	onError: function(files,status,errMsg)
	{		
		$("#status").html("<font color='red'>Upload is Failed</font>");
	}
}
$("#mulitplefileuploader").uploadFile(settings);

});
</script>
</body>

<div id=”mulitplefileuploader”>Upload</div> This div will be replace with the form and input file field and make some are for drag and drop image. <div id=”status”></div> Shows status of images and progress of uploading images.

upload.php

File contains post upload process and move files in uploads directory.

<?php
$output_dir = "uploads/";

if(isset($_FILES["myfile"]))
{
	$ret = array();

	$error =$_FILES["myfile"]["error"];
   {

    	if(!is_array($_FILES["myfile"]['name'])) //single file
    	{
            $RandomNum   = time();

            $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name']));
            $ImageType      = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.

            $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
            $ImageExt       = str_replace('.','',$ImageExt);
            $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
            $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

       	 	move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName);
       	 	 //echo "<br> Error: ".$_FILES["myfile"]["error"];

	       	 	 $ret[$fileName]= $output_dir.$NewImageName;
    	}
    	else
    	{
            $fileCount = count($_FILES["myfile"]['name']);
    		for($i=0; $i < $fileCount; $i++)
    		{
                $RandomNum   = time();

                $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
                $ImageType      = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

                $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
                $ImageExt       = str_replace('.','',$ImageExt);
                $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
                $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

                $ret[$NewImageName]= $output_dir.$NewImageName;
    		    move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName );
    		}
    	}
    }
    echo json_encode($ret);

}

?>

First check directory and error after that check if single file coming then process separate if multiple files handle in loop.

$RandomNum   = time();

$ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
$ImageType      = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

$ImageExt       = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt       = str_replace('.','',$ImageExt);
$ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName   = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

Add UNIX time stamp with image name to create unique name.

This tutorial contain code to download and a demo to show how it work i hope you like this please feel free to comment.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

119 responses to “How to Upload multiple images jQuery Ajax using PHP”

  1. tbz says:

    social button is overlapping the input field in your demo, makes it unusable 🙁

  2. Dezz Yung says:

    Good article!

    I will use this functionality to develop Prestashop Modules.

  3. Ahmet says:

    i can’t download it

  4. arpan says:

    i tried saving multiple images to my database table (using your code above ) for particular ID but i was not able to insert that id (passed in URL) in table . could you please help ?

  5. victor sotto says:

    how to save the details (filename and file path) of those files being uploaded in the database. please help

  6. how to get demo code

    • huzoorbux says:

      Click on download code button and it will take you to the download page if you are a subscriber then enter that email it will give you download link. Not subscribed yet then subscribe now.

    • huzoorbux says:

      Click on download code button and follow the instructions.

  7. download successfully

  8. jeffphpninja says:

    Nice, you have to wait 6 hours after subscription to be able to download. Guess I will unsubscribe then.

  9. Manisha says:

    Hi, May I please know how can I modify your code to have limit of uploading only 5 images. Reply asap

    • huzoorbux says:

      edit your plugin settings and add this

       
      var settings = {    
      url: "upload.php",    
      method: "POST",    
      allowedTypes:"jpg,png,gif,doc,pdf,zip",    
      fileName: "myfile",    
      multiple: true, 
      maxFileCount:5, 
      

      .

  10. Jack says:

    Thank you for sharing your code, How can I limit the file size ?

  11. sondos says:

    6 hours to confirm the subscribing !!!!!!!!!

  12. Freethinker says:

    Incredibly frustrating sharing method my friend.

  13. AJ Qucik says:

    Have you guys never heard of “View Source”? You can download the files directly off of the server. Copy the code from the text above.

    Thanks for the tutorial guys!

  14. Manisha says:

    Hi, I want to ask how can alert a message and stop user from pressing the next button untill the progress is 100%.

    • huzoorbux says:

      You can disable your next button by default and make it active once upload complete in this function of your jQuery.
      onSuccess:function(files,data,xhr){
      // make button active
      }

      • Manisha says:

        I already did what you said, but in case of multiple images. My button becomes active at first success of first image and for other cases it remains active.

        • huzoorbux says:

          Use this function in settings and add your button activate code:


          afterUploadAll:function()
          {
          //All files are uploaded activate button
          },

          • Manisha says:

            I tried what you said

            afterUploadAll:function()
            {
            $(‘#submitBtn’).removeAttr(‘disable’);
            },

            but its not working my button is disabled and remains disable even after successful upload of images.

          • Manisha says:

            Sorry, my mistake I used the code but no effect it enables after upload of very first image and remains enabled.

          • Manisha says:

            Hi, thanks for updating your code. But I want to show alert if someone clicks on submit button when progress bar is not 100% that is image is not uploaded yet.

          • Manisha says:

            Hi, Is there any possible solution available????

          • Manisha says:

            Hey, I solved my problem. I used

            onSelect:function()
            {
            //alert(“Wait untill image being uploaded !!”);
            $(‘#submitBtn’).attr(‘disabled’,’true’);
            $(‘#submitBtn’).addClass(‘disabled-button’);
            $(‘.disabled-div’).css(‘display’,’block’);
            },

          • huzoorbux says:

            I have updated the code and added trigger on all images upload, it will show an alert on all images upload please check above index.html script.

  15. Sagnik Dutta says:

    How can I modify it to show a thumbnail after uploading the image?

  16. neer says:

    I want to upload zip of image folder and then unzip and store all images path with name in mysql db .please help
    Thanks a lot for this tutorial.

  17. Madan Ray says:

    Hi

    I just want to pass file counter parameter to below function how it’s possible?

    onSuccess:function(files,data,xhr)
    {
    //
    }

    Thanks,

    Madan Kumar Ray

  18. Kenshero says:

    Hi. I want upload by button . I don’t want auto upload. Can you help me ?

  19. danish says:

    How to disallow the user to upload image which is more than 1Mb?

  20. danish says:

    How to implement size(Mb or Kb) restriction and image dimension restriction…?

    • Maurizio Zilli says:

      For the max size restriction You make .htacces file in upload folder with this content:

      php_value upload_max_filesize 10M
      php_value post_max_size 30M

  21. Suresh Kumar says:

    Should Show the thumbnail images after uploading the files

  22. Suresh Kumar says:

    Should Show the thumbnail images after uploading the files ,pls make it little bit faster

  23. Mark Bagnall says:

    Is it possible to pass another variable for example a gallery id $_POST[‘catId’];, I have tried but the upload function doesn’t seem to pick it up

    • huzoorbux says:

      Yes its possible you can post data by adding this line in settings:
      formData: {"catId":"Mark Bagnall"},

      • Mark Bagnall says:

        And to make it as a posted value, would I put in $_POST[‘catId’] or use some form of javascript to populate the value?

      • php_learner says:

        have u noticed the issue with if (is_array) condition? It will never be considered as array even if u upload multiple images suggest me something to solve this?

      • Alex says:

        I changed the “url” setting to this:
        url: “updr/upload.php?P=” + document.getElementById(‘lstP’).value,

        then I can use the $_GET[‘P’] variable in upload.php.

  24. Sher says:

    Great script thank you very much and works really well but can you
    please advise how to restrict each image upload size to a maximum 2Mb.

  25. Ramone says:

    if(!is_array($_FILES[“myfile”][‘name’])) is always not array of files although multiple files selected for upload??

    • php_learner says:

      thats right i am having the same issue even if you upload multiple images it will never consider it as array

  26. jaydip says:

    hello i use your code but how i insert all value in my sql

    db

  27. Sergio A. Guzmán says:

    may I wait almost 6 hours to download script?! bad done guys!
    well, I may to wait, thanks anyway 🙂

  28. stefan says:

    What’s this?! I subscribed to the mailing list… but still not able to download. crap!

  29. Nampen says:

    i don’t understand How can i change url : for use with codeigniter

  30. Tamas Norbert says:

    how to disable the maxfilesize ??

  31. php_learner says:

    Ur condition if(is_array(FILES[‘myfile’][‘name’])) never executes because it is never considered as array even when you upload multiple images so that is a bug in your program you should improve ur script

  32. Jonathan Odette Sengi says:

    it doesn’t save files in the said directory ( ‘uploads’), How can i save file in directory or db?

  33. Marcello Patto says:

    Hi man, great tutorial!
    I´ll use this to save users documents and need to save it on a MySQL database. How can I pass de user id to the php file?

    THKS!

  34. fazal says:

    sir,it is great tutorial.but how to display it using php.

  35. When open the index page, mulitplefileuploader div is hidden, but the form is not shown. What could be the problem? Excellent script 🙂

  36. fire brick says:

    Hello, I read your blogs. Your humoristic style is wonderful, keepdoing what you’re doing! And you can look our website http://refractory-brick.com/ about refractory brick manufacturer. Thank you very very much.

  37. Divyesh Jesadiya says:

    how can i do that with MYSQL?

    • Hafees Rahman says:

      you change the query into

      $ret[$NewImageName]= $output_dir.$NewImageName; //these code not work well

      $ret[‘fileName’]= $output_dir.$NewImageName;//change the line into these. it is associative array

      mysqli insertion

      ———————–

      $album=1;

      foreach($ret as $key=>$value){

      $sql=”INSERT INTO `image`(`album_id`, `image_url`) VALUES ($album,’$value’)”;

      if (mysqli_query($con, $sql)) {

      echo “New record created successfully”;

      } else {

      echo “Error: ” . $sql . ”
      ” . mysqli_error($con);

      }

      }

  38. Andrew says:

    Hi, You are not doing server-side validation for image type, anyone can upload anythig, if they bypass jquery validation.

  39. Dex says:

    Hi! Is it possible that all images will be uploaded in email? Thanks!

  40. Hafees Rahman says:

    thanks great full

    it contain a small error

    if you want to insert the data in to db table

    you change the query into

    $ret[$NewImageName]= $output_dir.$NewImageName; //these code not work well

    $ret[‘fileName’]= $output_dir.$NewImageName;//change the line into these. it is associative array

    mysqli insertion

    ———————–

    $album=1;

    foreach($ret as $key=>$value){

    $sql=”INSERT INTO `image`(`album_id`, `image_url`) VALUES ($album,’$value’)”;

    if (mysqli_query($con, $sql)) {

    echo “New record created successfully”;

    } else {

    echo “Error: ” . $sql . “” . mysqli_error($con);

    }

    }

  41. Manisha says:

    Hi, somehow this uploader is not working inside inbuilt browser of facebook android app.
    Is there any way to solve this issue?

  42. Ayuni Suraya says:

    Hi Huzoor Bux,

    How to delete file in file uploads?

    I change ‘Done’ to ‘Delete’.

    I used unlink but it doesn’t work anyway.

    Have you any idea about this?

    • Huzoor Bux says:

      try this if(unlink(FILENME)){ echo “Deleted”; } else{ echo “Error”; } and make sure that you have given correct path of file to unlink.

      • Ayuni Suraya says:

        Sir, below is my coding in upload.js and delete.php

        /********************upload.js**************/

        deleteCallback: function(data,pd)
        {
        for(var i=0;i<data.length;i++)

        {
        //alert(data[i])
        $.post("branch/more_examples/delete.php",{op:"delete",name:data[i]},
        function(resp, textStatus, jqXHR)
        {
        var hg2 =$('.stepContainer').height();
        $('.stepContainer').height(hg2+65)
        });
        }
        //pd.statusbar.hide(); //You choice to hide/not.

        }

        /************************end upload.js****************/

        /*********************delete.php**********************/
        include_once("../../Connections/dbConnect.php");
        $conn=$db;
        $dir = '/spk/dokumen/kenaikan_pangkat/';
        $output_dir = $_SERVER['DOCUMENT_ROOT'].$dir;
        if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
        {
        $fileName =$_POST['name'];

        $filePath = $output_dir.$fileName;
        if (file_exists($filePath))
        {
        unlink($filePath);
        $qry="delete from dokumen_kenaikan2 where nama_fail like '%$fileName%'";
        mysql_query($qry,$conn) or die(mysql_error());
        }
        echo "Deleted File ".$fileName."”;
        }

        /************************delete.php****************/

        But Sir, I still having problem in deleting file in uploads file. There is any wrong in my coding?

    • Huzoor Bux says:

      try this if(unlink(FILENME)){ echo “Deleted”; } else{ echo “Error”; } and make sure that you have given correct path of file to unlink.

  43. koundou says:

    Can anyone help hot to insert the photos into the database with mysql. i try but is not work.

  44. Huzoor Bux says:

    Your file looks fine.

    What is the problem try to debug code line by line where your script stop.

    • Ayuni Suraya says:

      Thanks Sir. May God Bless you.
      My upload file finally works and success. i found that i forget to link your jquery.form.js.

      Sir, if u dont mind, how i display back all file uploaded in my database?
      For example, if i want to allow system to update file that have been uploaded, i have to display back the uploaded file.

      I really appreciate if u give some tutorial about this. I’m newby in jquery. Your coding really helps me.

  45. Erhan Şentürk says:

    this code how mysql insert image system make. i need for my website ?id=1 for (5) < image added. id=1 page my add image view how.

    my mysql insert code example:

    new text added

    New Text ADD Form

    Head

    message

    Categories

    <?php

    $categories_cek = mysql_query("SELECT * FROM categories");

    while($categories_cek_new = mysql_fetch_array($categories_cek)){

    echo '’.$categories_cek_new[‘head’].”;

    }

    ?>

     

    <?php

    break;

    case "insertmysql":

    $text_head = str_replace("'", "'", $_POST['txt_head']);

    $text_message = str_replace("'", "'", $_POST['txt_message']);

    $text_categories = $_POST['slct_categories'];

    $date = date("d.m.Y");

    if(($text_head == "") or ($text_message == "")){ // if empty alert!

    echo 'alert(“Please no empty box!”);’;

    echo ”;

    }else{

    $makale_kaydet = mysql_query(“INSERT INTO text (head,message,date,categories) VALUES (‘$text_head’,’$text_message’,’$date’,’$text_categories’)”);

    echo ‘alert(“Text Added Successful!”);’;

    echo ”;

    }

    break;

    }

    ?>

  46. Sashtha manik says:

    hello sir this was so help full… i had one doubt from this topic …,if upload the image sucessfully after that how to know the image path ?

    The image path will show ??

  47. Atiar says:

    Hi,

    I need to pass custom data on upload.php and then need to insert the file info into database as well as the custom data.

    Please help…

    Thanks!
    Atiar

  48. Atiar says:

    Hi,

    I need to pass custom data on upload.php and then need to insert the file info into database as well as the custom data.

    Please help…

    Thanks!
    Atiar

  49. knnguler says:

    Hi How to upload Verot ?

  50. neil says:

    Hi Im trying to make the upload base on submit but cant seems to get it .basically what im trying to to is 1. click upload to browse for img file then click start upload to trigger the ajax to work but i cant find a way to to it. can you pls help me a bit.

    thanks

    neil

  51. Mike says:

    Hi,

    Thanks for the tutorial!

    Is it possible to do a tutorial with the above code and uploading to an Amazon S3 bucket?

  52. Exe To Doc says:

    Thanks for your tutssss…

  53. Ian says:

    I am trying this script but the upload button does not work on my website, I am unable to click on the upload button as I would prefer to use that than drag and drop please, can anyone help me

  54. ianhaney says:

    I got the upload button working now but how can I get the page to refresh automatically after upload so I can see the images uploaded?

  55. ianhaney says:

    Sorry have got it all working perfect now

  56. Vinicius Meca says:

    Hi, How can I limit the upload to 2 files at the same time? Default is 6 right?

  57. Vinicius Meca says:

    Hi, How can I limit the upload to 2 files at the same time? Default is 6 right?

  58. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  59. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  60. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  61. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  62. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  63. Mudassar Muhammad Khan says:

    Huzoor buksh you are greaaaaaaattt

  64. kishan says:

    please i cant download

    my email [email protected]

  65. kishan says:

    thank u so much

  66. kishan says:

    i upload 33 images which is 103mb most of file dosn’t upload please help

  67. abbas says:

    how we can define user roles in php

  68. abbas says:

    plz help me any body

  69. Teja Jakarulloh says:

    how to upload multiple image into database ?

  70. gulshan says:

    need multi video upload in wordpress…can u help?

  71. Jeboy Vega says:

    How to perform an sql insert data with this one?

  72. avinash says:

    please tell me how crop image according height in image uploader.

  73. FrozeN_BrainZ says:

    Thank you VERY much!

  74. dharmesh patel says:

    everything working fine but it generates new form for every new file so if we use it within another form then jquery validation will stop working.
    also cant upload mp3 file.

    • Dharmesh patel says:

      We can manage file size by ini file and hence file upload issue will solve, but there is still problem of multiple form generate….

  75. Dwi Ahmad says:

    how to add some description on each picture that I’ve select

  76. Dwi Ahmad says:

    how to add some description on each picture that I’ve select

  77. Dwi Ahmad says:

    how to add some description on each picture that I’ve select

  78. Nuju says:

    Is it possible to set the maxfileupload limit to one.

  79. เวอร์ซาเช่ สิทธิพงษ์ says:

    i like it .thank you so much.

  80. sabatini says:

    hi, redirect after upload is possible?

  81. Benoît Desprez says:

    Hi there,
    The script is perfectly fonctionnal but… I’d like to add 2 things and i can’t because i’m not a coder 🙂
    First, I’d like to have a preview of the uploaded images instead of the name of it, like . I can’t find where this info is displayed in the .js file to replace it…

    Finally, I’d like to add a php fuction to reduce the size, in pixels, of the uploaded images (maxfilesize). I’ve found many ways to do so but when I implant it ine the php code the upload doesn’t work anymore.
    Thank you for helping.

  82. nyxxxxxxx says:

    great script, ty:)

Leave a Reply

Your email address will not be published. Required fields are marked *