Multiple File Upload with PHP

Sometime we need to allow our users multiple file upload for flexibility. Uploading multiple is quite similar to simple upload but we need to do some modification. Today's almost top browsers supports  multiple file upload. Now I am going to show you a simple multiple file upload example.




HTML Form:
<!-- Multiple file upload html form-->
<form action="" method="POST" enctype="multipart/form-data">
	<input type="file" name="files[]" multiple="multiple">
	<button type="submit">Upload</button>
</form>

PHP Script:
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
	// Loop $_FILES to exeicute all files
	foreach ($_FILES['files']['name'] as $f => $name) {     
	    if ($_FILES['files']['error'][$f] == 4) {
	        continue; // Skip file if any error found
	    }	       
	    if ($_FILES['files']['error'][$f] == 0) {	           
	        if ($_FILES['files']['size'][$f] > $max_file_size) {
	            $message[] = "$name is too large!.";
	            continue; // Skip large files
	        }
			elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
				$message[] = "$name is not a valid format";
				continue; // Skip invalid file formats
			}
	        else{ // No error found! Move uploaded files 
	            if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
	            $count++; // Number of successfully uploaded file
	        }
	    }
	}
}

No comments:

Post a Comment