+40 745 232 788

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.

Leave a Reply to Fatih Cancel reply

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