Checking Mime-Type of External URL Using PHP

I was overwhelmed by Mime-Type while I was working for a project. The problem is I don’t know how to retrieve the mime-type from a file, particularly file from another host. This url is the one I want t check its mime-type. Why do I have to check it? Because it doesn’t have proper extension for an image. Look how it shows ‘?v=1423061058’ as its extension. What is it!!!??

I was thinking, oh I must get the file first and then opening it using fopen(). But, lately I found it so difficult. So, I Google it and I thought it was the effective solution provided by folks in StackOverflow. Here is the link. Then, I modified it.

<?php
	$filename = 'http://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2015/02/04/102396732-trequarti_basso.530x298.?v=1423061058';
	$file_info = new finfo(FILEINFO_MIME_TYPE);
	$mime_type = $file_info->buffer(file_get_contents($filename));
	echo $mime_type;
?>

Yeah it works! But it was not when I was working on Laravel 5 especially in a Controller. It seemed the Laravel couldn’t find the finfo class. I also found that method above was using so much resource. There must be less idiot way to get it works. Aha! The get_header() method saved me!

Hero Method of get_header()

Well, the get_header() is the best way to show the file mime-type of external url. The application of the method is also the easiest. With just using a single line $file = get_headers($url, 1) you’ll get a bunch of array values including mime-type of the file. Look at this.

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Using the echo $file['Content-Type'] will get you the result of its mime-type. That’s it!