Get Mime Type - Mission Impossible?

Discussion in 'PHP' started by MMJ, Oct 20, 2007.

  1. #1
    Why is there decent way in PHP to get the mime type?

    I have been searching extensively the past 3 days and it seems like there are three main ways, which each way having problems:

    1. mime_content_type()
    This is deprecated, alot of the times not installed, and if installed will sometimes not find the mime.magic file.

    2. file_info
    Wasn't installed on the hosts I tried, doesn't seem to have very good support. Is an extension (PECL).

    3. shell_exec(file -ib . $file)
    Doesn't work on windows servers. I tried it on a linux server and it gave me "image/x-3ds2" for a php file. WTF?

    Why doesn't something as common as mime have good support on php?

    What is a good, almost bullet proof way to get the mime type of a file?
     
    MMJ, Oct 20, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    That's the issue. There's no reliable way at the moment.

    But in PHP 6, the fileinfo extension will be improved and it'll be installed and enabled by default.

    At the moment the only more-or-less reliable way of getting the MIME type for images is using getimagesize(). For other file types we're a bit screwed up.

    (It can also be done via file extension recognition, but that's not reliable either, of course)
     
    nico_swd, Oct 20, 2007 IP
  3. rspenc29

    rspenc29 Peon

    Messages:
    256
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    There is no good or almost bullet proof way. I just use the following:

    function getMimeType($file_path)
    {
    	$mtype = '';
    	if (function_exists('mime_content_type')){
        	     $mtype = mime_content_type($file_path);
      	}
    	else if (function_exists('finfo_file')){
        	     $finfo = finfo_open(FILEINFO_MIME);
        	     $mtype = finfo_file($finfo, $file_path);
        	     finfo_close($finfo);  
      	}
    	if ($mtype == ''){
        	     $mtype = "application/force-download";
      	}
    	return $mtype;
    }
    Code (markup):
     
    rspenc29, Oct 20, 2007 IP
  4. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #4
    If you really need a way you can read the file headers and extract the type from it.

    Peace,
     
    Barti1987, Oct 20, 2007 IP
  5. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yeah, I figured out as much. That sucks.

    That'll be a nice improvement.

    Yeah, I'm thinking of using something like this:

    http://www.google.com/codesearch?q=...dle/mod/wiki/ewiki/plugins/lib/mime_magic.php
     
    MMJ, Oct 22, 2007 IP