Accurately checking file mime type using PECL fileinfo

K, I need a proper accurate way of detecting mime type of the uploaded file, instead of using standard $_FILES['userfile']['type'] which rely on the browser information - this is not accurate!.

Tried renaming my flash file (.flv) into extension .mpg, and the $_FILES['userfile']['type'] will return "video/mpeg".

The PHP's fileinfo module is the much better checker in doing this... this is how I managed installing the fileinfo module into my system...


Installing PECL fileinfo module

Firstly, ensure you have pecl installed in your system, just do "which pecl" will give you information if the pecl installed. If not install it using your prefered method.
In my centos server i did "yum install php-pear"

Next install the fileinfo, simply type:

pecl install fileinfo

On my laptop which runs two version of php (PHP5 and PHP4 cgi) I need two times, one the standard one and as for the PHP4 cgi, i need to execute directly from pecl of the PHP4 cgi:

/usr/local/php4/bin/pecl install fileinfo

If you got the error like "Couldn't find package phpize" install the php development package first (php5-dev, php-devel or other that you are using)

And if you got error something like "Please reinstall the libmagic distribution" then install it! :p :

sudo apt-get install libmagic-devel

Once done, edit your php.ini, add the following:

extension=fileinfo.so

restart your web server and see phpinfo, you should see fileinfo module listed in the module list.

Finally, copy your magic files to /etc folder:

cp /usr/share/file/magic* /etc/

Using Fileinfo module to check mimetype in PHP

PHP5 & PHP4 handle the fileinfo checks differently. PHP5 is using object oriented style in handling fileinfo while PHP4 uses standard non OO method.

Since I'm using both PHP5 and PHP4, and I don't want to bother what version of PHP my script will be running on, then I uses this:

$mime_type = null;
/*if the server using php4 then this function exist*/
if (function_exists('finfo_open')){
$handle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($handle,$file['tmp_name']);
}
 
/*if the server using php5 then this class will be used instead*/
if (class_exists('finfo')){
$handle = new finfo(FILEINFO_MIME);
$mime_type = $handle->buffer(file_get_contents($file['tmp_name']));
}

where $file is my $_FILES upload.

:)

Tags: , , , , ,
Linux & Open Source, PHP, Programming & Web Devt, at work |

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

I just got the error on my CentOS server saying ‘can’t load magic database on /usr/share/misc/magic’.

Actually there’s already symbolic link from /usr/share/misc/magic to the real file… after copying the files instead using symbolic.. the error gone… so seem symbolic links will not work in this…

Leave a comment

(required)

(required)