How to upload Multiple Files in PHP

In this tutorial, we will learn How to Upload Multiple Files in PHP with an example.

Upload Multiple Files in PHP with an example

Contents

HTML

Creating a index.php file.

Create an input type='file' element and for enabling multiple files selection add multiple the attribute in it.

For reading all selected files when <form> submitted please add [] brackets at the end of a name that denotes an Array. Like: name="uploadedFile[]"

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

PHP

Create a upload folder to store image files at the root directory.

When the form is submitted, we count files by the PHP array count function.

count($_FILES['uploadedFile']['name']) and loop through all files.

Upload Multiple Files in PHP – Code

<?php
  //check file selected or not.
if (isset($_FILES['upload']['name'])) {
  // count files
  $filesCount = count($_FILES['upload']['name']);
  // Loop through each file
  for ($i = 0; $i < $filesCount; $i++) {
    //Get the filename.
    $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
    //Make sure we have a file path
    if ($tmpFilePath != "") {
      //Setup The destination of the moved file.
      $newFilePath = "upload/" . $_FILES['upload']['name'][$i];
      //Upload file
      if (move_uploaded_file($tmpFilePath, $newFilePath)) {
        //Handle other code here
      }
    }
  }
  echo "Files uploaded.....";
}
?>

Output

Download source code

Be First to Comment

Leave a Reply

Your email address will not be published.