Multiple files upload using HTML and PHP

Are you trying to upload multiple files at once ? Here’s how to implement multiple files upload using HTML and PHP.

In this article, I am going to show how to use a single HTML file input to upload multiple files. In addition to that, I will demonstrate using multiple file inputs with additional input fields.

Implementing multiple files upload

Firstly, you need to create a HTML form with attribute enctype=’multiple/form-data’. In fact, the enctype attribute specifies how the form-data should be encoded when submitting it to the server. When you are using forms that have a file upload control, you need to specify enctype as multiple/form-data.

If you are using single file input, you need to enable your file element to select multiple files. In order to do this, you need to name your file input as an array, eg. name=”files[]” . Also, File Input element must have multiple=”multiple” or just multiple.

The HTML form will look like as follows:

<form action="" method="post" enctype="multipart/form-data">
  <label> Select Files: </label>
  <input type="file" name="fileUpload[]" multiple > 
  <input type="submit" name="Submit" value="Upload" >
</form>

When user submits the form after selecting files, we can process the form using simple PHP snippets as follows:

<?php

// Set Upload Path
$target_dir = 'files/';

if( isset($_FILES['fileUpload']['name'])) {
      
  $total_files = count($_FILES['fileUpload']['name']);
  
  for($key = 0; $key < $total_files; $key++) {
    
    // Check if file is selected
    if(isset($_FILES['fileUpload']['name'][$key]) 
                      && $_FILES['fileUpload']['size'][$key] > 0) {
      
      $original_filename = $_FILES['fileUpload']['name'][$key];
      $target = $target_dir . basename($original_filename);
      $tmp  = $_FILES['fileUpload']['tmp_name'][$key];
      move_uploaded_file($tmp, $target);
    }
    
  }
     
}

?>

Validating file type and file size

You can restrict file type by checking extension of the uploaded file with set of allowed extensions. The following code checks for valid image file.

// Get the extension
$ext = strtolower(pathinfo($_FILES["fileUpload"]["name"][$key], PATHINFO_EXTENSION));
        
// check extension and upload
if( in_array( $ext, array('jpg', 'jpeg', 'png', 'gif', 'bmp'))) {
  // Filetype if valid, process uploading
}

In order to check the file size, you can use $_FILES[‘image’][‘size’] as follows:

$maxFileSize = 5 * 1024 * 1024; //5MB
$errors = array();

if($_FILES['fileUpload']['size'][$key] > $maxFileSize){
  $errors[$key] = 'File size is greater than allowed size';
}

Furthermore, you can also rename filename before uploading. Here’s how to replace spaces within filename with underscore and add timestamp to the filename.

if(isset($_FILES['fileUpload']['name'][$key]) 
                  && $_FILES['fileUpload']['size'][$key] > 0) {
  
  
  $original_filename = $_FILES['fileUpload']['name'][$key]; 
     
  // Get the fileextension
  $ext = pathinfo($original_filename, PATHINFO_EXTENSION);  
    
  // Get filename without extesion
  $filename_without_ext = basename($original_filename, '.'.$ext);
  // Generate new filename
  $new_filename = str_replace(' ', '_', $filename_without_ext) . '_' . time() . '.' . $ext; 
  // Upload the file with new name
  move_uploaded_file($_FILES['fileUpload']['tmp_name'][$key], $target_dir . $new_filename);
}

Uploading multiple files with additional information

Sometimes it is required to upload multiple files with additional information like title, description, etc. In such cases, you have to use several file input controls.

Multiple Files Upload Using PHP

In the above screenshot, each file input has corresponding title. Here’s the sample HTML.

<form action="" method="post" enctype="multipart/form-data"> 
  
  <input type="text" name="title[]" placeholder="Title" >
  <input type="file" name="fileUpload[]" > 
  
  <input type="text" name="title[]" placeholder="Title" >
  <input type="file" name="fileUpload[]" > 
  
  <input type="text" name="title[]" placeholder="Title" >
  <input type="file" name="fileUpload[]" > 
  
  <input type="text" name="title[]" placeholder="Title" >
  <input type="file" name="fileUpload[]" > 
  
  <input type="submit" name="Submit" value="Upload" > 
  
</form>

As you can see, there is multiple text input and file input controls. By appending ‘[]’ to your input element names, input elements will submit as arrays.

When you submit the above form, $_POST[‘title’] will be an array. By matching the index of array $_POST[‘title’] with $_FILES[‘fileUpload’][‘name’], you can get corresponding title, filename pair. For instance, $_POST[‘title’][0] is the title of file $_FILES[‘fileUpload’][‘name’][0] and so on.

In this way, you can implement multiple file uploads using HTML and PHP.

You can also upload multiple files using AJAX.

You may also like: Inserting multiple rows into MySQL using PHP

4 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.