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
-
$finfo = finfo_open();
-
-
$fileinfo = finfo_file($finfo, $file, FILEINFO_MIME);
-
-
finfo_close($finfo);
or you can also use OOP based syntax like
-
$finfo = new finfo;
-
-
$fileinfo = $finfo->file($file, FILEINFO_MIME);
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.
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...
Thanks for appreciation. Could you please elaborate on what is the problem you have on Windows XP.
Amit