article

Saturday, February 19, 2022

JavaScript PHP upload multiple files

JavaScript PHP upload multiple files

index.html
//index.html
<!DOCTYPE html>
<html>
<head>
	<title>JavaScript PHP upload multiple files</title>
</head>
<body>
	<div>
		<p><h1>JavaScript PHP upload multiple files<h1></p>
		<input type="file" name="files" id="files" multiple>
		<input type="button" id="btn_uploadfile" value="Upload" onclick="uploadFile();">
	</div>

<script type="text/javascript">
	function uploadFile() {

		var totalfiles = document.getElementById('files').files.length;
		
		if(totalfiles > 0 ){ 

			var formData = new FormData();
			
			// Read selected files
		   	for (var index = 0; index < totalfiles; index++) {
		      	formData.append("files[]", document.getElementById('files').files[index]);
		   	}

			var xhttp = new XMLHttpRequest();

			// Set POST method and ajax file path
			xhttp.open("POST", "ajaxfile.php", true);

			// call on request changes state
			xhttp.onreadystatechange = function() {
			    if (this.readyState == 4 && this.status == 200) {
			      	
			      	var response = this.responseText;

			      	alert(response + " File uploaded.");
			      	
			    }
			};
			
			// Send request with data
			xhttp.send(formData);

		}else{
			alert("Please select a file");
		}
		
	}
</script>
</body>
</html>
ajaxfile.php
//ajaxfile.php
<?php 
// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";
    
$count = 0;
for($i=0;$i<$countfiles;$i++){

	// File name
    $filename = $_FILES['files']['name'][$i];

    // File path
	$path = $upload_location.$filename;

    // file extension
	$file_extension = pathinfo($path, PATHINFO_EXTENSION);
	$file_extension = strtolower($file_extension);

	// Valid file extensions
	$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");

	// Check extension
	if(in_array($file_extension,$valid_ext)){

		// Upload file
		if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$path)){
		    $count += 1;
		}	
	}
                 
}

echo $count;
exit;

Related Post