PHP multiple files upload example will show you how to upload multiple files using PHP. In this example the files are selected using the browse buttons and files are uploaded to the ‘uploads’ directory under root project directory. 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.

The below HTML form is required in order to upload multiple files.

<form name="upload_form" enctype="multipart/form-data" action="uploadFiles.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>

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 we also check if the same file already exists in the destination directory then we don’t need to upload the same file.

<?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'];
				}
			}
		}
	}
}
?>

The complete source code is given below

<!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="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></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 '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'];
                        }
                    }
                }
            }
        }
        ?>
        <div id="container">
            <form name="upload_form" enctype="multipart/form-data" action="uploadFiles.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>

Testing the application

Run the above file to get the below output on browser and select any files and upload

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 ooe file must be selected for upload.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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