File validation example in PHP

This tutorial shows how to allow only specific file types to be uploaded to the server. In this example I have shown how to allow only Microsoft word document and pdf file types. You can add more file types here.

We need to validate the file type for whenever we allow user to upload a file which can be an avatar, a picture or any other type of file for some security reasons.

The below array holds allowed types of files

$allowedExts = array(


The each file type has a MIME type so we have to check that also. Below array holds MIME types for MS Word and pdf types.

$allowedMimeTypes = array(


Get the file extension from the file name. Look carefully here, end function is used to retrieve only the last part because there might be multiple . in a file name.

$extension = end(explode(".", $_FILES["file"]["name"]));

Check allowed file extensions

if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide correct file type .');
} else {
// upload file and do further processing

Check allowed MIME types for file and upload the file to the appropriate destination

if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) ) {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
} else {
die('Please provide correct file type .');


That’s all. Thanks for your patience. Please do not forget to leave a comment.

Leave a Comment