January 13, 2014 12:42 pm

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

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.

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

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

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:
  • tbz

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

    • huzoorbux

      It looks fine to me what browser you are using?

  • Dezz Yung

    Good article!

    I will use this functionality to develop Prestashop Modules.

    • qizhi

      Can you get me demo?

  • Ahmet

    Vey Good

  • Ahmet

    i can’t download it

  • arpan

    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 ?

    • victor sotto

      did you get any answer? 🙂

  • victor sotto

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

  • how to get demo code

    • huzoorbux

      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

      Click on download code button and follow the instructions.

  • download successfully

  • jeffphpninja

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

  • Manisha

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

    • huzoorbux

      edit your plugin settings and add this

      .

  • Jack

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

  • sondos

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

  • Freethinker

    Incredibly frustrating sharing method my friend.

  • AJ Qucik

    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!

  • Manisha

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

    • huzoorbux

      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

        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

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


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

          • Manisha

            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

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

          • Manisha

            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

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

          • Manisha

            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

            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.

  • Sagnik Dutta

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

  • neer

    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.

  • Madan Ray

    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

  • Kenshero

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

    • Madan Ray

      You can use normal upload method

      • Kenshero

        How i do?

  • danish

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

  • danish

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

    • Maurizio Zilli

      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

  • Suresh Kumar

    Should Show the thumbnail images after uploading the files

  • Suresh Kumar

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

  • Mark Bagnall

    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

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

      • Mark Bagnall

        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

        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

        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.

  • Sher

    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.

  • Ramone

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

    • php_learner

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

  • jaydip

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

    db

  • Sergio A. Guzmán

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

  • stefan

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

  • Nampen

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

  • Tamas Norbert

    how to disable the maxfilesize ??

  • php_learner

    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

  • Jonathan Odette Sengi

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

  • Marcello Patto

    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!

    • umanga sudesh

      Hi did you solve this problem. Please can you explain. it.
      Thank you

  • fazal

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

  • Superneminator@gmail.com

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

    • Nemanja

      I cannot find where is mulitplefileuploader is made hidden. It is not in css, index.html nor js files.

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

  • Divyesh Jesadiya

    how can i do that with MYSQL?

    • Hafees Rahman

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

      }

      }

  • Andrew

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

  • Dex

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

  • Hafees Rahman

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

    }

    }

    • Chew Kok

      could not work 🙁

  • Manisha

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

  • Ayuni Suraya

    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?

    • 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

        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?

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

  • koundou

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

    • Please share your code so i can help you to fix that.

    • Sashtha manik

      please avoid to insert the image directly into database 🙂

    • Jagjit singh

      try this
      $q=”insert into gallery(images) values(‘$ret[$fileName]’)”;
      $result=mysql_query($q);

  • Your file looks fine.

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

    • Ayuni Suraya

      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.

  • Erhan Şentürk

    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;

    }

    ?>

  • fsdfdfd

    sdff

  • Sashtha manik

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

  • Atiar

    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

  • Atiar

    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

  • knnguler

    Hi How to upload Verot ?

  • neil

    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

  • Mike

    Hi,

    Thanks for the tutorial!

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

  • Exe To Doc

    Thanks for your tutssss…

  • Ian

    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

  • ianhaney

    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?

  • ianhaney

    Sorry have got it all working perfect now

  • Vinicius Meca

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

  • Vinicius Meca

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

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • Mudassar Muhammad Khan

    Huzoor buksh you are greaaaaaaattt

  • kishan

    please i cant download

    my email erkishu97@gmail.com

  • kishan

    thank u so much

  • kishan

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

  • abbas

    how we can define user roles in php

  • abbas

    plz help me any body

  • Teja Jakarulloh

    how to upload multiple image into database ?

  • gulshan

    need multi video upload in wordpress…can u help?

  • Jeboy Vega

    How to perform an sql insert data with this one?

  • avinash

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

  • FrozeN_BrainZ

    Thank you VERY much!

  • dharmesh patel

    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

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

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

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

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