How to Upload and Validate Files using PHP

arp14 HTML, PHP, Tutorial Tags: , , , , , 8

Howdy coders,

In this post, I’m going to show you how to upload and validate files using PHP. At first we’ll need a simple HTML form with an input type=”file”, then we’ll catch the uploaded file from PHP using $_FILES[“file”]. Then we’ll validate it by extension, mime-type and file size; then process it further.

Our validation condition will be as below:

  • Allowed file type: Word processing / Document files and pdf files
  • Allowed extensions: doc, docx, odt and pdf
  • Allowed file size: less than 100 kB

Upload and Validate Files using PHP

	<title>Upload & Validate files using PHP -</title>

$error = "";
if (isset($_FILES["file"])) {
	$allowedExts = array("doc", "docx", "pdf", "odt");
	$temp = explode(".", $_FILES["file"]["name"]);
	$extension = end($temp);

	if ($_FILES["file"]["error"] > 0) {
		$error .= "Error opening the file<br />";
	if ( $_FILES["file"]["type"] != "application/pdf" &&
			$_FILES["file"]["type"] != "application/vnd.openxmlformats-officedocument.wordprocessingml.document" &&
			$_FILES["file"]["type"] != "application/msword" &&
			$_FILES["file"]["type"] != "application/vnd.oasis.opendocument.text") {	
		$error .= "Mime type not allowed<br />";
	if (!in_array($extension, $allowedExts)) {
		$error .= "Extension not allowed<br />";
	if ($_FILES["file"]["size"] > 102400) {
		$error .= "File size shoud be less than 100 kB<br />";

	if ($error == "") {
		echo "uploaded successfully";
	} else {
		echo $error;

<form action="upload.php" method="post" enctype="multipart/form-data">
	<label for="file">Filename:</label>
	<input type="file" name="file" id="file" /><br />
	<input type="submit" name="submit" value="Submit" />


I hope its useful for you.

For other data fields server side validation using PHP, see this post.

If you need any help, just leave a comment.

Thank you!

8 thoughts on “How to Upload and Validate Files using PHP

  1. thanks for the code.. helped me 🙂 I wish i could donate you guys but i am not from a high standard country and family too..,, so, sry n Someday may be i will ..

  2. how to check the real file? not only the extension? If only extension check, there a lot article out there and your post seen only copy paste….. useless!!!

Leave a Reply

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