PHP (Core & Framework)

Multiple files upload at once with PHP

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.

First, create a <form> and add enctype='multiple/form-data' attribute.

  • 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 HTML 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);
    
 }
} 
?>

Complete Code (HTML & PHP)

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>

Comment here

81 − 75 =