Multiple file upload using PHP and jQuery

Hello folks, in your coding work day, you may need to develop file upload for your project. Most of the time, when we search for file upload, we need lot of plugins to achieve the functionality. Today, we will see some code where you can upload multiple files only using jQuery Ajax.

Files structure we done with:

I have created 3 files for better understanding, so that code of PHP, Javascript and HTML code will be separate out. Also created the upload folder where the uploaded files will go.

project-root/
    ->upload/
    ->index.php
    ->upload.js
    ->upload.php

HTML – Where our simple design will reside:

We haven’t done with any design for this tutorial. It just have a simple upload field and button to upload files.

<html>
<head>
  <title>Multiple File Upload Demo</title>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
  <script src="upload.js"></script>
</head>
  <form id="fileForm" action="upload.php" enctype="multipart/form-data">
    <input type='file' id='uploadfile' name='file[]' multiple />
    <button type="button" id="btn_upload">Upload File</button>
  </form>
</html>

Upload – jQuery Ajax upload:

We simply use jQuery ajax, we all are familiar with it. It is pretty much simple than including dozens of plugins into the application.

$(document).ready(function(){

  $("#btn_upload").click(function(e){
    e.preventDefault();

    var files = $('#uploadfile')[0].files;
            
    var formData = new FormData();
    
    for(var i=0; i<files.length; i++) {
      formData.append('file'+i, $('#uploadfile')[0].files[i]);
    }

    formData.append('file_count', files.length);

    $.ajax({
      url: "upload.php",
      type: "POST",
      data: formData,
      dataType: "json",
      enctype: 'multipart/form-data',
      processData: false,
      contentType: false,
      success: function(data) {
        if(data['upload'] == 'success') {
          alert("files uploaded successfully");
        } else {
          alert(data['upload']);
        }
      }
    });
  
  });

});

Actual upload – PHP upload script:

Here we accept the files from PHP Global variable $_FILES and pickup files from it. Move to upload directory finally.

<?php

$upload_dir = 'upload/';

for($i = 0; $i < $_POST['file_count']; $i++) {
  $file_name = $_FILES['file'.$i]['name'];
  $file_tmp = $_FILES['file'.$i]['tmp_name'];
    
  move_uploaded_file($file_tmp, $upload_dir.$file_name);
}

$result['upload'] = 'success';
echo json_encode($result);

If you execute it, you can upload multiple files at a time using above simple code snippets.

Limitations:

In above code, we haven’t done with any file size validations, file extension validations. You can add it as per your business requirements.