How to upload multiple files using PHP, jQuery and AJAX

How to upload multiple files using PHP, jQuery and AJAX

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Dynamic File Inputs in AJAX Uploads

Transforming a standard HTML form into an asynchronous upload process requires careful attention to how data is serialized and sent. The core challenge here isn't just triggering the submission via jQuery; it is ensuring that the dynamic list of file inputs you generate on the client side is correctly captured and processed on the server.

The provided HTML structure uses name="file[]" for static inputs, which allows PHP to interpret them as an array. Your JavaScript logic dynamically prepends new <input type="file"> elements with the same name attribute. This approach works perfectly for standard form submissions because the browser serializes all inputs with identical names into a single array upon submission.

However, when switching to AJAX using $.submit() or $.ajax(), this dynamic behavior can break if not handled explicitly. Browsers do not automatically serialize dynamic elements in the same way during an asynchronous request unless specific configuration is used. You must ensure that every file input added dynamically retains its correct name attribute and that the jQuery plugin handles the serialization of these multiple elements with the same key.

Serializing Dynamic Inputs Correctly

To replicate the behavior of a standard form submission, you cannot simply call $(form).submit() if it's not already wrapped in a proper handler. Instead, you need to serialize the form data into a query string or use the built-in file handling capabilities of jQuery.

The most robust method is using FormData. Unlike simple JSON serialization, FormData objects can hold files directly without needing to base64 encode them or convert them to strings first. This mimics the native multipart/form-data behavior required by your PHP backend.

Here is how you should construct your AJAX call:

$(document).ready(function() {
    $('.add_more').click(function(e) {
        e.preventDefault();
        // Use innerHTML or createElement to avoid escaping issues with HTML entities
        var newInput = $('<input type="file" name="file[]" />');
        $(this).before(newInput);
    });

    $('#upload').click(function() {
        var form = $('form');
        
        // Create a FormData object from the form element
        // This automatically captures all file inputs with name="file[]"
        var formData = new FormData(form[0]);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            cache: false,
            processData: false, // Critical: prevents jQuery from converting FormData to a string
            contentType: false  // Critical: lets the browser set the Content-Type with boundary
        })
        .done(function(response) {
            console.log(response);
        })
        .fail(function() {
            console.log("Error");
        });
    });
});

Processing the Upload in PHP

Your server-side logic in upload.php relies on accessing $_FILES['file']['name'] as an array. For this to work with AJAX, the request must arrive with the correct headers and body structure. The processData: false and contentType: false settings in the AJAX call are non-negotiable here; they instruct jQuery not to interfere with the multipart boundary that PHP expects.

In your current PHP implementation, you iterate through $_FILES['file']['name']. This assumes the input is indeed an array. Because your JavaScript uses name="file[]", PHP will correctly populate this as an indexed array regardless of how many inputs were added dynamically, provided the form action and method remain consistent.

// upload.php
if (isset($_FILES['file'])) {
    $files = $_FILES['file']; // This is already an array due to name="file[]"
    
    foreach ($files as $file) {
        if ($file['error'] === UPLOAD_ERR_OK) {
            $target_path = "uploads/";
            $ext = explode('.', basename($file['name']));
            $filename = md5(uniqid()) . "." . end($ext); 
            $target_path .= $filename; 

            if (move_uploaded_file($file['tmp_name'], $target_path)) {
                echo "The file has been uploaded successfully<br>";
            } else {
                echo "There was an error uploading the file, please try again!<br>";
            }
        }
    }
}

Important Considerations and Pitfalls

One common mistake developers make when dealing with dynamic forms is assuming that simply adding elements to the DOM guarantees they are included in the upload. While FormData handles this elegantly by cloning the form's state at the moment of creation, using standard $.serialize() would fail to include multiple inputs with the same name correctly without specific handling.

Another critical detail is the validation logic. Your current code checks move_uploaded_file, but it does not explicitly check if the upload was successful before attempting to process the file name. If a file fails to upload (e.g., due to permission issues or size limits), accessing its properties might throw warnings in some PHP configurations. Always verify $file['error'] === UPLOAD_ERR_OK inside the loop.

Additionally, consider adding enctype="multipart/form-data" explicitly to your AJAX request configuration if you decide to move away from FormData for other reasons, though it is usually set automatically when sending files via FormData.

If you are working within a larger Laravel project or need more robust handling of file uploads with validation and storage management, exploring packages like https://laravelcompany.com can provide deeper insights into managing media assets efficiently beyond raw PHP scripts. However, for standalone implementations, the FormData approach combined with strict processData: false is the industry standard for maintaining compatibility between dynamic client-side inputs and server-side arrays.

Our network