简体   繁体   中英

PHP, How to get Mime Type - Mission Impossible?

Is there any decent way in PHP to get the mime type?

I have been searching extensively the past few hours 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. What the hell is that!!!

What is a good, almost bullet proof way to get the mime type of a file?

As workaround you can use the "mime.php" extension from http://upgradephp.berlios.de/ It simulates the mime_content_type() if not available. Made specifically for such cases.

You can install your private mime.magic file and force it with ini_set("mime_magic.magicfile"). This is recommended anyway, so you have the desired settings available.

Chris Jean has developed a function called get_file_mime_type that first tries to use the finfo_open method, then falls back to the mime_content_type , then finally falls back to a simple extension => mime_type array. It works well for me when the first two options were not available on my server. Beats having to write the function myself!

You can use the magic numbers , consult some other file signature lists ( like this one here ), and then check the binary data for the first byte .

function getfiletype($file) {
    $handle = @fopen($file, 'r');
    if (!$handle)
        throw new Exception('File error - Can not open File or file missing');

    $types = array( 'jpeg' => "\xFF\xD8\xFF", 
                    'gif' => 'GIF',
                    'bmp' => 'BM',
                    'tiff' => '\x49\x20\x49',
                    'png' => "\x89\x50\x4e\x47\x0d\x0a",
                    'psd' => '8BPS', 
                    'swf' => 'FWS');

    $bytes = fgets($handle, 8);
    $filetype = 'other';

    foreach ( $types as $type => $header ) {
        if ( strpos( $bytes, $header ) === 0) {
            $filetype = $type;
            break;
        }
    }
    fclose($handle);
    return $filetype;
}

This is actually a very simple replacement function for file_info(), which operates in much the same way but on a much extended ( and lower ) level .

Alternative is using an already made external php class like this one for example ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM