PHP Multiple File Uploads

Example: PHP Multiple File Uploads

Looking for how to upload multiple files in PHP? This article is going to give an in-depth tutorial on how to upload Multiple files and Images in PHP.

PHP multiple file uploads give your users an easier task, instead of uploading files one by one.

How to Upload Multiple Files in PHP

To upload multiple files, you will need to take care of the following points:

  • HTML input name should be defined as an array i.e. name = "fileUploads[]";
  • Input tag must have an attribute called multiple with a value of multiple i.e. multiple="multiple"
  • In your PHP use the following syntax to get file data: $_FILES['inputName']['param'][index]

With those 3 points in mind, we can go ahead and start our project.

Please make sure you read how to get file extensions in PHP; we will need this concept while validating the file extension before uploading.

The following code illustrates how to perform multiple file upload in PHP:





<!DOCTYPE html>
<html>
<head>
  <title>PHP Multiple file uploads</title>
</head>
<body>
  <form method="post" action="uploads.php" enctype="multipart/form-data">
    <input type="file" name="uploadFiles[]" multiple="multiple"><br /><br /> 
    <input type="submit" value="upload">
  </form>
</body>
</html>

The following code shows the upload process with PHP Script (uploads.php)

<?php 

// time to upload our files 

if(isset($_FILES['uploadFiles']['name'])){
  $totalFiles = count($_FILES['uploadFiles']['name']); 

  $allowedExtensions = array(".png", ".jpg", "jpeg", ".zip", ".gif");

  $start = 0; 
  while($start < $totalFiles){

    $tmp = $_FILES['uploadFiles']['tmp_name'][$start]; 
    $eachFileSize = $_FILES['uploadFiles']['size'][$start];
    $eachFileName = $_FILES['uploadFiles']['name'][$start]; 

    // you can check the size of each file
    if($eachFileSize > 20000000 ){
      // if there is a file greater than 2mbs, then  return
      echo $eachFileName." is greater than 2mbs. The upload proceess has been terminated"; 
      exit(); // kill the loop
    }

    $eachFileExtension = strtolower(substr($eachFileName, strlen($eachFileName)-4, strlen($eachFileName))); 

    // check for illigal file extensions

    if(in_array($eachFileExtension, $allowedExtensions)){
      // now we can upload
      $location = "uploads/".$eachFileName;
      move_uploaded_file($tmp, $location); 
    } else {
      // terminate the loop 
      echo $eachFileName." Contais illigal extension, the upload process has been terminated!";
      exit(); 
    }

    // check for extensios
    // allow images only

    echo $eachFileName." has been uploaded to ".$location."<br />"; 

    $start ++; 
  }
}