Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

[How To] Use of PHP’s fileinfo extension to get file’s MIME type

In previous post, one of my colleague Jatin introduced you to one of the new features of PHP-5.3, PHAR. I am going to take a look at one more PHP-5.3 feature Fileinfo which was a PECL extension prior to PHP-5.3.

So first of all let’s re-phrase Fileinfo’s job as per PHP manual, which says, the functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file.

What’s the use of guessing content type of a file you may ask? In any PHP application, most of the time, you need to check if uploaded file is of correct MIME type or not. Fileinfo helps you to do this instead of relying on ‘type’ value in $_FILES array (which uses uploaded file’s extension to judge ‘type’, depends on browser).

The basic syntax to get file’s MIME type using fileinfo is

or you can also use OOP based syntax like

In above syntax if $file contains full path of a file then $fileinfo will contain its MIME type, for example, ‘image/jpeg’ for JPG file or ‘text/x-php’ for PHP file. If you don’t use FILEINFO_MIME or used FILEINFO_NONE instead then $fileinfo will contain textual representation of file’s type, something like, ‘JPEG image data’ or ‘PHP script text’.

If you have content of a file instead of full path then use ‘finfo_buffer($content)’ instead of ‘finfo_file($file)’ or ‘$finfo->buffer($content)’ instead of ‘$finfo->file($file)’.

P.S. You can also use ‘file -bi $file’ shell command using exec() or passthru() or system() on linux systems if fileinfo is not available and/or you are allowed to run shell commands using PHP.

About the Author

Amit Badkas is Zend certified PHP5 and Zend Framework engineer, and has been working in SANIsoft for past 10 years, his present designation is ‘Technical Manager’

4 comments

  1. Hi, i enjoyed your article about PHP’s fileinfo extension, but i can’t get it to work here on Windows XP, any ideas? I’ve tried everything…

      • PHP 5.2.13 doen’t include php_fileinfo.dll extension. downloading php_fileinfo.dll and copying into my ext directory won’t effect because of his version. do you have any solution for this.

Leave a Reply