Page 1 of 1

Mime-type madness

Posted: Wed Jul 06, 2011 6:05 am
by ben.artiss
Hi,

I've been trying to find a reliable way of determining a file's mime-type, so I tried two different methods on the same file and got different results (neither of which I expected to see in the first place!). Method 1 uses PHP's fileinfo functions, and method 2 uses unix's file command. The file I tested it on was a text file, so I expected to see "text/plain".

Code: Select all

<?php
/**
 * Get mime type using PHP finfo
 */
function file_mime_type_1($path)
{
	if ( ! file_exists($path)) return FALSE;

	$finfo  = finfo_open(FILEINFO_MIME_TYPE);
	$result = finfo_file($finfo, $path);

	finfo_close($finfo);

	return $result;	
}

/**
 * Get mime type using unix file command
 */
function file_mime_type_2($path)
{
	if ( ! file_exists($path)) return FALSE;

	$result = `file -b --mime-type {$path}`;
	$result = strtolower($result);

	if (substr($result, 0, 5) == 'error') return FALSE;

	return $result;
}
?>

<p>Using PHP finfo: <?= file_mime_type_1('/path/to/example.txt') ?></p>
<p>Using unix file: <?= file_mime_type_2('/path/to/example.txt') ?></p>
The results were:
[text]Using PHP finfo: text/x-lisp
Using unix file: text/x-c++ [/text]
Does anyone know of an alternative way, or should I just hack around this?

P.S. Does anyone know which is quicker?

Re: Mime-type madness

Posted: Wed Jul 06, 2011 7:29 am
by ben.artiss
Sorry.. ignore that! After a bit more reading it seems mime-types are bit of a mission impossible until PHP6.