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

 

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.

 

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.

Check allowed file extensions

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

 

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

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.