Determinate mime type from MySQL column

可紊 提交于 2019-11-30 23:18:40

IF your host still uses php 5.2 and dont have access to the fileinfo functions you can test the files header signature (magic numbers) to determine mime type

function mimetype($data)
{
    //File signatures with their associated mime type
    $Types = array(
    "474946383761"=>"image/gif",                        //GIF87a type gif
    "474946383961"=>"image/gif",                        //GIF89a type gif
    "89504E470D0A1A0A"=>"image/png",
    "FFD8FFE0"=>"image/jpeg",                           //JFIF jpeg
    "FFD8FFE1"=>"image/jpeg",                           //EXIF jpeg
    "FFD8FFE8"=>"image/jpeg",                           //SPIFF jpeg
    "25504446"=>"application/pdf",
    "377ABCAF271C"=>"application/zip",                  //7-Zip zip file
    "504B0304"=>"application/zip",                      //PK Zip file ( could also match other file types like docx, jar, etc )
    );

    $Signature = substr($data,0,60); //get first 60 bytes shouldnt need more then that to determine signature
    $Signature = array_shift(unpack("H*",$Signature)); //String representation of the hex values

    foreach($Types as $MagicNumber => $Mime)
    {
        if( stripos($Signature,$MagicNumber) === 0 )
            return $Mime;  
    }

    //Return octet-stream (binary content type) if no signature is found
    return "application/octet-stream"; 
}

NOTE: Some signatures may match partials of others, for instance the PK Zip file signature matches the first 4 bytes of java archive (.jar) file signature, extra statements would be needed in the foreach loop to determine the correct signature for the mime type, but for your situation this should do.

A updated list of file signatures can be found at http://www.garykessler.net/library/file_sigs.html if someone needs more file signature types.

The FileInfo extension, and, more specifically, its finfo_buffer() function, might help, here (quoting) :

This function is used to get information about binary data in a string.

Fetching your binary data from database, and passing it to this function, might do the trick.


Note : its comes with PHP >= 5.3

Save the blob to a temp file and use the php finfo_file function on it.

The FileInfo extension can be used. It contains a function called finfo_buffer()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!