Multiple files upload at once with PHP

In PHP, it is possible to upload multiple files using a 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. Demo
  5. 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 that 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 selected 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. Demo

View Demo


5. Conclusion

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

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

Make sure to check upload_max_filesize and post_max_size values in the php.ini file if you are allowing large files to upload.

If you found this tutorial helpful then don't forget to share.