+44 (0) 7918 168 992

Online Solutions Development Blog   |  

RSS

Create multiple file uploader using php, html and jQuery.

posted by ,
Categories: PHP
Taggs , , ,

When you have to upload an unknown number of files with php, adding some jQuery script can make your job a lot easier than you think. On this post I’ll show you how to do that in no time and effortless.

First, let’s create the html form and add two “buttons” that will be used for adding or removing an uploading field from the form.

<span class="add_field">+</span>
<span class="remove_field">-</span>

<form action="upload.php" method="POST" enctype="multipart/form-data">
	<div class="input_holder">
		<input type="file" name="uploaded_files[]" id="input_clone"/>
	</div>
	<input type="submit" value="upload_files" />
</form>

The span elements will be out add/remove buttons so we’ll add a listener to them to know when someone want to add or remove a field from the form.

Because it’s an uploading form, we have to specify that to the browser. We do this by adding enctype=”multipart/form-data” as an attribute to the form.

Also we add a file input type which has a unique id which will allow us to clone the element as many times as we want. The name of the field is given as an array in order to be able to stock up multiple data information without being forced to stock them with different names or add numbers or any other way of messing up the code.

After this, let’s add the listener on the buttons so the “unknown number of fields” to be feasible.

 
<script type="text/javascript">

        $('.add_field').click(function(){
	
            var input = $('#input_clone');
            var clone = input.clone(true);
            clone.removeAttr ('id');
            clone.val('');
            clone.appendTo('.input_holder'); 
		
        });

        $('.remove_field').click(function(){
		
            if($('.input_holder input:last-child').attr('id') != 'input_clone'){
                  $('.input_holder input:last-child').remove();
            }
		
        });

</script>

Now let’s explain this part.

When the user clicks the ‘.add_field’ button we have to do several actions.

var input = $('#input_clone');

Here we get the first input of the field by its id.

var clone = input.clone(true);

We clone the element.

clone.removeAttr ('id');

Remove the id attribute. We don’t want on the same page to have 2 or more elements with the same id.

clone.val('');

Here we remove the value of the input. This way we make sure that the user will not upload, by mistake, the same file twice or several times.

clone.appendTo('.input_holder'); 

And last but not least we add the input to the div that holds them.

After we finished with the adding part, maybe the user abused too much of the “+” button and there are way too many input fields. Let’s make possible for him to remove them.

First thing first here, we have to make sure that he does not abuse of the “-” button and remove all input files. We test if the input it’s not the original one (has the unique id), and if doesn’t have it we remove it.

And now, our last step of this article is the php file that handles the uploading.

<?php 

if(isset($_FILES ['uploaded_files']))
{
     foreach($_FILES['uploaded_files']['name'] as $key=>$value)
     {
          if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES[['uploaded_files']['error'][$key] == 0)
          {
              	$filename = $_FILES['uploaded_files']['name'][$key];
                $filename = time().rand(0,999).$filename;
                            
                if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], 'uploads/'. $filename))
                {
               	      echo 'The file '. $_FILES['uploaded_files']['name'][$key].' was uploaded successful';
                }
                else
                {
                      echo 'There was a problem uploading the picture.';
                } 
          }
          else
          {
   	        echo 'There is a problem with the uploading system.';
          }
     }
}

?>

Here, first time you check if there are any files that need to be uploaded, by checking if the $_FILES variable is set. If there are any files ready for upload, then for each file you have to check if the file was successfully uploaded and if there are no errors. If so, your next step is to make sure your file has a unique name. On this I use a little trick renaming my file based on the current time and a random number and the filename. This way, the possibility of 1 or more users to upload a file with the same name is almost, if not, 0.

The last step is to check if the file was moved on the upload folder. If everything goes well you will get, for each file, a message that will tell you that the file was successfully uploaded.

There are a few problems that might occur and you can avoid them by:
1. Make sure the uploading folder exists. The move_uploaded_file() function will not automatically create it for you.
2. If you want you can set a limit for the files. This limit has to be equal or lesser than post_max_size located in your php.ini file.
3. The uploading folder has to have the permission for writing on.

You can download the file.

If you have something to say about this subject please feel free to use the comment form below.

If you liked this post
you can buy me a beer

24 Responses to Create multiple file uploader using php, html and jQuery.

  1. technical but very clearly

  2. Very nice>>>> 🙂 got an answer thanks

  3. Nice job man…I’m looking for something like this…
    Its works so perfectly….
    Once again thanks…..

  4. Thank you Catalin! Its very clean and good Code.. Working very well.. Now i can easily interact and stored in database.

    • Can u tell me how can i insert it now into databse plz..

      • Hello,

        The sample provided with this article has a php file called upload.php. The first lines of the file handle the logic needed for uploading the file and in that same area you could as well add some other logic like saving a record to a database table, getting the generated key to use it as file name, adding validations on file types or sizes and anything else you could think of.

        You could as well change the form action and process the files in a separate file or include the logic you have in a framework/template engine that separates the html from the php.

        The focus of this tutorial was to show the cloning and removing of DOM elements (file inputs in this case) and also the fact that you could send an array of files (see the naming: uploaded_files[]) and it is not meant to cover any aspect that might be related to any file upload.

        If you want to learn about database interaction I recommend you to use PDO and the best resource is for sure the official documentation: http://php.net/PDO

  5. I want to using like this script but i want to send my email adress not files just inputs, please help me.

    • Hello, Fatih. What do you want to receive to your email address? The uploaded files? As attachments or download links?

      • hi mishu thanks for reply, i have a form with cloned elements, and i want to post to my adress this form but when i post this form i get just first input into form , cloned input dont post this is my form link

        • Hello,
          First of all the link you sent is broken (it redirects to a page named “website under review”).
          Second, the inputs should be available when you submit the form. If they are not please double check if you used the naming convention for arrays (the [] in the name, see that the file input int his example is named uploaded_files[])

          • Thanks again. this is new link my form: http​:/​/​mesalemilling​.com​/dark/
            i dont know how post it please help me

            • Hello,
              First of all I would like to say that I merged all the 3 comments you posted for this in just one (this one, I am replying to) to keep the conversation clear. The content is exactly the same.
              Second: I am sorry, but I don’t know Turkish so I can’t navigate on that page very well, but what is the exact problem? What do you get in post.php as $_POST? Did you try to print that content with print_r/var_dump ?

  6. Thanks for merged comments and yes i want to $_POST all cloned input my email adress with this form. But its not working when i try to $_POST just first input come my email adress.

  7. $name = stripslashes($_POST['name']); //sender's name
    $email = stripslashes($_POST['email']); //sender's email
    $phone = stripslashes($_POST['phone']); //sender's website
    $firma = stripslashes($_POST['firma']);
    $urun = stripslashes($_POST['urun']);
    $adet = stripslashes($_POST['adet']);
    $tarih = stripslashes($_POST['tarih']);
    
    $msg  = "Kimden : $name \r\n"; 
    $msg .= "E-Mail : $email \r\n";  
    $msg .= "Telefon : $phone \r\n";
    $msg .= "Firma İsmi : $firma \r\n";
    $msg .= "Malın Cinsi : $urun \r\n";
    $msg .= "Adet: $adet \r\n"; 
    $msg .= "Teslim Tarihi : $tarih \r\n";
    $msg .= "---Mesajı--- \r\n".stripslashes($_POST['message'])."\r\n\n";
    $msg .= "---User information--- \r\n"; //Title
    $msg .= "User IP : ".$_SERVER["REMOTE_ADDR"]."\r\n"; //Sender's IP
    $msg .= "Browser info : ".$_SERVER["HTTP_USER_AGENT"]."\r\n"; //User agent
    $msg .= "User come from : ".$_SERVER["HTTP_REFERER"]; //Referrer
    
    	if  (mail($to, $urun, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
    
  8. Hi thanks,
    yes me too 🙂 how can i do? any ideas?

    • what I was asking was in fact: why are you asking this here? I can’t see any connection to the subject of this blog post. All the fields you are using are straight from the _POST array, there’s nothing to suggest that there’s a problem with the multiple file uploader or with cloning elements. If your _POST request doesn’t have some of the fields this is an unrelated issue. I would be glad to help you when I have time but I think that we are “polluting” the discussion with unrelated discussions. You could as well try to post your question on stackoveflow

  9. Thank you for answers i m sorry for distrubing you

    • You are welcome. That’s for sure no problem, I am just trying to keep the discussions on topic. Maybe for more general discussions we should open a forum also. We will analyze other people’s opinion also to find out if that would be truly useful or yet another forum in the ocean of already available ones.

  10. hi,
    i ve downloaded your code, very nice ,
    the problem is, the files stored in folder uploads can’t be opened or corrupted
    i ve set the permission for the upload folder

    • Hello, Azam.

      The purpose of this tutorial is to show how you can clone and remove elements from the page and how you can handle multiple files uploaded at the same time.

      It is not recommended to use this exact file in a live application as the file upload is handled only at a minimum level. You can see that there is no validation done on the files and that the names are the original ones with just a prefix added. That is usually a bad idea but here we just showed how the multiple files are uploaded, it is up to you to secure and customize your script, there was no point for this tutorial to cover every possible type of job.

      If the files are corrupted it is likely that your problem is not related to the permissions on that directory as the script does write them. You should check the limitations imposed by your server settings. Some directives in your php.ini file that could affect this are
      • The max_file_uploads value that sets the maximum numer of files allowed to be uploaded simultaneously
      post_max_size that sets the total size of data that can be sent via POST
      • and most likely for you case if every file is corrupted: upload_max_filesize that represents the maximum size of an uploaded file

      You should also check if the script does show any message after the file upload as it should tell you for each file if it was successfully uploaded or not. I hope that this helps you find your problem.

Add a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc