Skip to content

Validating files by mime type

Uploading file in a form is always very critical. When you give your users functionality to upload some file on your site, you open many doors hackers to your site. Hackers can upload files suiting their purpose and exploit your site code. So you must check the type of file which is going to be uploaded. We have 3 methods to do this:

  1. Splitting the file name by dot(.) to get the extension and then based on this extension, decide file type.
  2. system(“file -bi — “.escapeshellarg($filename)) : Check type of file based on extension of its name. This method utilizes shell command to process.
  3. mime_content_type($filename) : This is PHP’s default method to check mime type of a file.
  4. FILEINFO: Probably the Best, as it provides extra information about file along with file type.

From above 4 methods, first 2 are prone to hacking techniques e.g. Hacker can spoof by renaming his script file with .jpg or .png etc. “FILEINFO” and “mime_content_type” methods are most accurate as they decide the type based on file’s mime time. Based on same mime type operating system decides program, to run scripts. Following is a function to demo how to use “FILEINFO” to check extension. This extension needs “php_FILEINFO” extension installed on the server.

This can be also used in Object-oriented style.

“mime_content_type” function is much shorter to use

Published inBlogPHP