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(
      "pdf",
      "doc",
      "docx"
);

 

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(
  'application/msword',
  'application/pdf'
);

 

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.

Soumitra Roy Sarkar

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 *