Multiple files upload at once with PHP

In PHP, it is possible to upload multiple files using single input file element. You just need to customize your single file upload PHP code and enable your file element to select multiple files.

In this tutorial, I show you how to implement multiple files upload with PHP.

Multiple files upload at once with PHP


Contents

  1. HTML
  2. PHP
  3. Completed Code
  4. Conclusion

 

1. HTML

Here, are some steps to enable multiple files uploads in <form>.

Steps

  • First, create a <form> and add enctype='multiple/form-data' attribute.
<form method='post' action='' enctype='multipart/form-data'>
  • Create an input type='file' element and for enabling multiple files selection add multiple attribute. For reading all selected files when <form> submitted add [] brackets at the end of a name which denotes an Array.
<input type="file" name="file[]" id="file" multiple>
  • Add a submit button.

Completed Code

<form method='post' action='' enctype='multipart/form-data'>
 
 <input type="file" name="file[]" id="file" multiple>
 <input type='submit' name='submit' value='Upload'>

</form>

 

2. PHP

When <form > method submitted first count files and loop through all files. Select files on the bases of index.

Completed Code

<?php 
if(isset($_POST['submit'])){
 // Count total files
 $countfiles = count($_FILES['file']['name']);
 
 // Looping all files
 for($i=0;$i<$countfiles;$i++){
   $filename = $_FILES['file']['name'][$i];
   
   // Upload file
   move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
    
  }
 }
} 
?>

 

3. Completed Code

<?php 
if(isset($_POST['submit'])){
 
 // Count total files
 $countfiles = count($_FILES['file']['name']);

 // Looping all files
 for($i=0;$i<$countfiles;$i++){
  $filename = $_FILES['file']['name'][$i];
 
  // Upload file
  move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
 
 }
} 
?>
<form method='post' action='' enctype='multipart/form-data'>
 <input type="file" name="file[]" id="file" multiple>

 <input type='submit' name='submit' value='Upload'>
</form>

 

4. Conclusion

I didn’t apply any restriction in the upload PHP script but it’s better to add restriction when you are implementing this in your project.

If you are using more than one file element for the single task then you can use above PHP script as a replacement.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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