Find MIME Type of File in PHP


Read {count} times since 2020

MIME type is needed to know what kind of file we’re looking at. HTML files have the MIME type text/html , for gif image, it’s image/gif and so on.

Since PHP is a dynamic content creator language, MIME type is a very important thing you should know about in PHP. In this small post, I’ll tell you how to find the MIME type of a local file in your server.

Enable Fileinfo Extension

For this, we need to enable the PHP fileinfo extension in php.ini. Add this into your php.ini file it doesn’t already exist :


And restart the Web Server. The restarting is different on various web servers. If it’s Apache you can do this command :

sudo service apache2 restart

Get the MIME Type

We will make a function to get the MIME type easily. We’ll call it "getMIMEType" :

function getMIMEType($filename){
 $finfo = finfo_open();
 $fileinfo = finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
 return $fileinfo;

Or you can make it easy by using the finfo object :

function getMIMEType($filename){
 $finfo = new finfo;
 return $finfo->file($filename, FILEINFO_MIME_TYPE);

But, I think the OO (Object Oriented) way will be slower than the other. It’s your choice, but they will both work in the same way.

And here’s how you can use it. Just pass the location of the file to it and it will return the MIME type :

echo getMIMEType("myfile.html");

In the above case, it will return :


Here are some more examples :

getMIMEType("myimage.jpeg"); // Returns image/jpeg
getMIMEType("myfile.js"); // Returns application/x-javascript
getMIMEType("myCss.css"); // Returns text/css

Use it as you wish.

Show Comments