tags:

views:

43

answers:

2

In OS X, if I use Photoshop (for instance) to create a PNG file, I have the option to save the file without an extension and OS X still recognizes what type of file it is and what application to open it with.

Is there any way for me to extract that information from a physical file using PHP?

Thanks in advance.

+1  A: 

The first eight bytes of a PNG file always contain the following (decimal) values: 137 80 78 71 13 10 26 10

You can use PHP to read file headers and deduce the file type from known headers. you can find this information quite readily on the internet in each format's spec (JPG, Bitmaps, GIF, PNG, whatever)

Here, I'll start you off: - PNG Spec

snicker
+1  A: 

Hi,

If you're using a recent enough version of PHP (ie 5.3) or have the possibility to install PECL extensions, you should take a look at the Fileinfo extension, that's bundled with PHP 5.3.

Quoting one of the given examples, a portion of code like this one :

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

Might get you something like this :

text/html
image/gif
application/vnd.ms-excel


If you're stuck with an older version of PHP, and cannot install PECL extensions, maybe the mime_content_type function would do.

Pascal MARTIN