I’m working on a project where the users can upload files, and I need to know the type of file they are uploading, a simple solution would be to check the extensions of the files, but this has many flaws, so I was looking for a reliable way to detect the type of file, and I found a PECL extension called file info this extension is enabled by default in PHP 5.3, unfortunately I’m running PHP 5.2.10, and the prod server also has this version.

So what I did to install this on ubuntu 9.10 karmic was the following:

  1. root@mini:/etc/php5/apache2# apt-get install php5-dev libmagic-dev php-pear
  2. ....
  3. root@mini:/etc/php5/apache2# pear channel-update pear.php.net
  4. ...
  5. root@mini:/etc/php5/apache2# pecl install Fileinfo
  6. ....
  7. Build process completed successfully
  8. Installing '/usr/lib/php5/20060613+lfs/fileinfo.so'
  9. install ok: channel://pear.php.net/Fileinfo-1.0.4

and finally I added the extension to php.ini

extension=fileinfo.so

I restarted the apache server, and tested with this

  1. $fileInfo = new finfo(FILEINFO_MIME);
  2. $mimeType = $fileInfo->buffer(file_get_contents($uploadedFile));