PHP Multiple Files Upload Example

Multiple Files Upload

PHP multiple files upload example will show you how to upload multiple files using PHP and AJAX using jQuery. In this example the files are selected using the browse buttons and files are uploaded to the uploads directory under project’s root directory. Make sure uploads directory exists under your project’s root folder.

PHP script stores the files into the defined location and returns response as a success or failure message from the PHP script. As a validation step I have added only to check if you have selected at least one file for uploading or not.

You may want to read also PHP Single File Upload Example

This tutorial will give you more attachment link for uploading file, so you will click on Attach another file then you will get Choose File button to attach another file. If you do not want to upload the chosen file then you can delete the attached file using Delete link.

Prerequisites

PHP 7.4/8.2.7, jQuery 3.5.1/3.7.1, Apache HTTP Server (Optional)

Client Side Code

The below HTML form is required in order to upload multiple files. Another solution to upload multiple files without using AJAX in jQuery is to add multiple="true" or multiple to the input type file field.

<form name="upload_form" enctype="multipart/form-data" action="files_upload.php" method="POST">
	<fieldset>
		<legend>Upload Multiple File(s)</legend>
		<section>
			<label>Browse a file</label>
			<label>
				<input type="file" name="upload_file1" id="upload_file1" readonly="true"/>
			</label>
			<div id="moreFileUpload"></div>
			<div style="clear:both;"></div>
			<div id="moreFileUploadLink" style="display:none;margin-left: 10px;">
				<a href="javascript:void(0);" id="attachMore">Attach another file</a>
			</div>
		</section>
	</fieldset>
	<div>&nbsp;</div>
	<footer>
		<input type="submit" name="upload" value="Upload"/>
	</footer>
</form>

Below jQuery code snippets are required in order to attach more file and delete the selected file if you do not want to upload the chosen file. The function attaches more file upload links when you select a file for uploading. Even you can delete the selected file if you think that the file you have selected is not needed or incorrectly selected.

<script type="text/javascript">
    $(document).ready(function () {
        $("input[id^='upload_file']").each(function () {
            var id = parseInt(this.id.replace("upload_file", ""));
            $("#upload_file" + id).change(function () {
                if ($("#upload_file" + id).val() !== "") {
                    $("#moreFileUploadLink").show();
                }
            });
        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function () {
        var upload_number = 2;
        $('#attachMore').click(function () {
            //add more file
            var moreUploadTag = '';
            moreUploadTag += '<div class="element"><label for="upload_file"' + upload_number + '>Upload File ' + upload_number + '</label>';
            moreUploadTag += '&nbsp;<input type="file" id="upload_file' + upload_number + '" name="upload_file' + upload_number + '"/>';
            moreUploadTag += '&nbsp;<a href="javascript:void" style="cursor:pointer;" onclick="deletefileLink(' + upload_number + ')">Delete ' + upload_number + '</a></div>';
            $('<dl id="delete_file' + upload_number + '">' + moreUploadTag + '</dl>').fadeIn('slow').appendTo('#moreFileUpload');
            upload_number++;
        });
    });
</script>

<script type="text/javascript">
    function deletefileLink(eleId) {
        if (confirm("Are you really want to delete ?")) {
            var ele = document.getElementById("delete_file" + eleId);
            ele.parentNode.removeChild(ele);
        }
    }
</script>

Server Side Code

Below PHP code is required for validating and uploading files into uploads folder under root project directory. It is absolutely recommended that before you upload file to a directory, you check whether file has been selected for uploading. Here I also checked if the same file already exists in the destination directory then you don’t need to upload the same file again.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
	if ($_FILES['upload_file1']['size'] <= 0) {
		echo 'Hey, Please choose at least one file';
	} else {
		foreach ($_FILES as $key => $value) {
			if (0 < $value['error']) {
				echo 'Error during file upload ' . $value['error'];
			} else if (!empty($value['name'])) {
				if (file_exists('uploads/' . $value['name'])) {
					echo 'Hey, File already exists at uploads/' . $value['name'];
				} else {
					move_uploaded_file($value['tmp_name'], 'uploads/' . $value['name']);
					echo 'File successfully uploaded to uploads/' . $value['name'];
				}
			}
		}
	}
}
?>

Client and Server Code

The complete source code is given below by putting all above code snippets together:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Upload Multiple File(s)</title>
        <style type="text/css">
            body {
                background-color: #fff;
                margin: 40px;
                font: 13px/20px normal Helvetica, Arial, sans-serif;
                color: #4F5155;
            }
            #body{
                margin: 0 15px 0 15px;
            }
            #container{
                margin: 10px;
                width: 600px;
                padding: 10px;
                border: 1px solid #D0D0D0;
                -webkit-box-shadow: 0 0 8px #D0D0D0;
            }
        </style>
        <!--<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="   crossorigin="anonymous"></script>-->
        <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    </head>
    <body>
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
            if ($_FILES['upload_file1']['size'] <= 0) {
                echo 'Hey, Please choose at least one file';
            } else {
                foreach ($_FILES as $key => $value) {
                    if (0 < $value['error']) {
                        echo nl2br('Error during file upload ' . $value['error'] . "\n");
                    } else if (!empty($value['name'])) {
                        if (file_exists('uploads/' . $value['name'])) {
                            echo nl2br('Hey, File already exists at uploads/' . $value['name'] . "\n");
                        } else {
                            move_uploaded_file($value['tmp_name'], 'uploads/' . $value['name']);
                            echo nl2br('File successfully uploaded to uploads/' . $value['name'] . "\n");
                        }
                    }
                }
            }
        }
        ?>
        <div id="container">
            <form name="upload_form" enctype="multipart/form-data" action="files_upload.php" method="POST">
                <fieldset>
                    <legend>Upload Multiple File(s)</legend>
                    <section>
                        <label>Browse a file</label>
                        <label>
                            <input type="file" name="upload_file1" id="upload_file1" readonly="true"/>
                        </label>
                        <div id="moreFileUpload"></div>
                        <div style="clear:both;"></div>
                        <div id="moreFileUploadLink" style="display:none;margin-left: 10px;">
                            <a href="javascript:void(0);" id="attachMore">Attach another file</a>
                        </div>
                    </section>
                </fieldset>
                <div>&nbsp;</div>
                <footer>
                    <input type="submit" name="upload" value="Upload"/>
                </footer>
            </form>
        </div>        
    </body>
</html>

<script type="text/javascript">
    $(document).ready(function () {
        $("input[id^='upload_file']").each(function () {
            var id = parseInt(this.id.replace("upload_file", ""));
            $("#upload_file" + id).change(function () {
                if ($("#upload_file" + id).val() !== "") {
                    $("#moreFileUploadLink").show();
                }
            });
        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function () {
        var upload_number = 2;
        $('#attachMore').click(function () {
            //add more file
            var moreUploadTag = '';
            moreUploadTag += '<div class="element"><label for="upload_file"' + upload_number + '>Upload File ' + upload_number + '</label>';
            moreUploadTag += '&nbsp;<input type="file" id="upload_file' + upload_number + '" name="upload_file' + upload_number + '"/>';
            moreUploadTag += '&nbsp;<a href="javascript:void" style="cursor:pointer;" onclick="deletefileLink(' + upload_number + ')">Delete ' + upload_number + '</a></div>';
            $('<dl id="delete_file' + upload_number + '">' + moreUploadTag + '</dl>').fadeIn('slow').appendTo('#moreFileUpload');
            upload_number++;
        });
    });
</script>

<script type="text/javascript">
    function deletefileLink(eleId) {
        if (confirm("Are you really want to delete ?")) {
            var ele = document.getElementById("delete_file" + eleId);
            ele.parentNode.removeChild(ele);
        }
    }
</script>

Start Development Server

Now to start the development server, navigate to the root folder of your project from the command line tool and execute the command: php -S localhost:80.

Your development server will start and listen to port 80.

Testing Multiple Files Upload Application

Run the above file by hitting the URL http://localhost/php-multiple-files-upload/files_upload.php or http://localhost/files_upload.php and you will see below output on browser:

php multiple files upload

When you choose a file and select then only you will be able to see the attach more file upload link otherwise not. You may choose more file or delete the selected file if you don’t want to upload. The delete link appears just right of the attach more file upload link but for the default upload link you won’t get any delete link because at least one file must be selected for upload.

Select few files as shown below:

php multiple files upload

On successful files upload you will see similar to the below message:

php ajax file upload

That’s all about how to upload multiple files using PHP and AJAX in jQuery.

Source Code

Download

Leave a Reply

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