Sunday 22 December 2013

How to get MIME type for the file in PHP

Today, we are going to see how to get MIME Type for the file in PHP.  In order to get the MIME Type we will use mime_content_type() methods, but this method has been deprecated. so instead we are going to use Fileinfo. Let's see the implementation.

Source Code:

$options = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$finfo = finfo_open($options);

if($finfo){
           $filename = 'application/log/jan21-2013.txt';
           echo finfo_file($finfo,$filename);
           finfo_close($finfo);
}

The above code will display the below output
text/plain

Instead of text (.txt) file name, let's consider the pdf file.

$options = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$finfo = finfo_open($options);

if($finfo){
           $filename = 'application/doc/setup.pdf';
           echo finfo_file($finfo,$filename);
           finfo_close($finfo);
}

The above code will display the below output
application/pdf

For more detailed information regarding the usage of finfo_open() and other methods, please refer the official documentation site.

Hope, you enjoyed this Post.


No comments:

Post a Comment