AJAX Multiple Files Upload using PHP, jQuery

Introduction

The example, AJAX multiple files upload using PHP jQuery, will show you how to upload multiple files using PHP, AJAX and jQuery without page refresh. This multiple files upload tutorial example is very useful where you need to upload multiple files in a web application.

In this example multiple files are selected using the browse button by holding keyboard’s Ctrl button and files are uploaded to the ‘uploads’ directory. PHP script stores multiple files into the defined location and returns responses as success or failure messages from the PHP script.

If you want more file upload link without holding Ctrl button when you select a file, then you may read PHP multiple files upload.

As a validation step I have added only to check if you have selected at least one file for uploading or not.

Related Posts:

Prerequisites

Apache HTTP Server 2.4, PHP 7.4.3, jQuery 3.4.1 – 3.5.1

Multiple Files Upload Process

Following steps are required in order to complete the example ajax multiple files upload using php jquery. Please go through the following steps.

  1. Include jQuery library.
  2. HTML page with upload field.
  3. jQuery Ajax code.
  4. PHP script to store the file.

Step 1. Include jQuery library into <head/> section of the HTML page. As the example AJAX multiple files upload using PHP jQuery suggests and you know without jQuery or JavaScript technology AJAX will not work, so it is required to include jQuery library.

You may also use plain JavaScript to apply AJAX technique but jQuery provides many more functionalities ad easy to use.

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Or

<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>

Step 2. Put the below upload field inside <body/> tag in HTML page.

Notice here how the name attribute is used. I have also used multiple attribute to indicate that I will upload multiple files.

<p id="msg"></p>
	<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
	<button id="upload">Upload</button>

Step 3. Add below jQuery, AJAX code immediate after the jQuery library inside <head/> section of the HTML page.

When Upload button is clicked then I first create a new FormData object to store the file data.

I first retrieve the file counts and store each file into FormData object.

I then finally send the file data using php-multiple-files-upload.php file where server side code is written for uploading to the destination directory.

<script type="text/javascript">
	$(document).ready(function (e) {
		$('#upload').on('click', function () {
			var form_data = new FormData();
			var ins = document.getElementById('multiFiles').files.length;
			for (var x = 0; x < ins; x++) {
				form_data.append("files[]", document.getElementById('multiFiles').files[x]);
			}
			$.ajax({
				url: 'php-multiple-files-upload.php', // point to server-side PHP script 
				dataType: 'text', // what to expect back from the PHP script
				cache: false,
				contentType: false,
				processData: false,
				data: form_data,
				type: 'post',
				success: function (response) {
					$('#msg').html(response); // display success response from the PHP script
				},
				error: function (response) {
					$('#msg').html(response); // display error response from the PHP script
				}
			});
		});
	});
</script>

Step 4. Create php-multiple-files-upload.php file with below source code.

This file is responsible for validation and uploading files to destination directory.

The PHP code first checks whether a user has selected at least one file for upload. If user has not selected at least one file then show an error message to the user for selecting at least one file.

Then code checks if the selected file already exists in the destination directory then inform with message that the selected file already exists in the destination directory otherwise upload the selected file in the destination directory.

<?php

if (isset($_FILES['files']) && !empty($_FILES['files'])) {
    $no_files = count($_FILES["files"]['name']);
    for ($i = 0; $i < $no_files; $i++) {
        if ($_FILES["files"]["error"][$i] > 0) {
            echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
        } else {
            if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
                echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
            } else {
                move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
                echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
            }
        }
    }
} else {
    echo 'Please choose at least one file';
}
    
/* 
 * End of script
 */

If I combine the steps 1, 2, and 3 then the full source code would be as shown below in a file called index.html.

<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function (e) {
			$('#upload').on('click', function () {
				var form_data = new FormData();
				var ins = document.getElementById('multiFiles').files.length;
				for (var x = 0; x < ins; x++) {
					form_data.append("files[]", document.getElementById('multiFiles').files[x]);
				}
				$.ajax({
					url: 'php-multiple-files-upload.php', // point to server-side PHP script 
					dataType: 'text', // what to expect back from the PHP script
					cache: false,
					contentType: false,
					processData: false,
					data: form_data,
					type: 'post',
					success: function (response) {
						$('#msg').html(response); // display success response from the PHP script
					},
					error: function (response) {
						$('#msg').html(response); // display error response from the PHP script
					}
				});
			});
		});
	</script>
</head>
<body>
	<p id="msg"></p>
	<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
	<button id="upload">Upload</button>  
</body>
</html>

Testing the Application

Home Page

Hit the URL http://localhost/php-ajax-jquery-multiple-files-upload/ in the browser and you will see output as shown below in the image:

ajax multiple files upload using php jquery

Error Message

When you do not select any file and try to click on Upload button then you will see the following error message:

ajax multiple files upload using php jquery

Uploading File(s)

Try to select multiple files (using Ctrl key) and click on Upload button.

ajax multiple files upload using php jquery

If the file successfully uploaded then you will see success message “File successfully uploaded : uploads/<some-file-name>“.

If the file you are trying to upload already exists then you will see a message “File already exists : uploads/<some-file-name>“.

Hope you have got an idea on AJAX multiple files upload using PHP jQuery.

Source Code

Download

6 thoughts on “AJAX Multiple Files Upload using PHP, jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *