PHP checks the uploaded image and returns the real type of the image [extension]

<?php

$file = @fopen('包含路径的文件名', "rb");
$bin = fread($file, 15); //只读15字节 各个不同文件类型,头信息不一样。
$flag = get_type_list($bin);
if(!empty($flag)) {
    echo $flag;
}
else{
    echo '不存在';
}
   
/**
* 得到文件头与文件类型映射表*
* author wengxianhu
* @param $bin string 图片的二进制前一段字符
* @return boolean
*/
public function get_type_list($bin)
{
    $flag = '';
    $array = array(
        array("FFD8FFE1","jpg"),
        array("89504E47","png"),
        array("47494638","gif"),
        array("FFD8FFE000104A46", "jpeg")
//         array("49492A00","tif"),
//         array("424D","bmp"),
//         array("41433130","dwg"),
//         array("38425053","psd"),
//         array("7B5C727466","rtf"),
//         array("3C3F786D6C","xml"),
//         array("68746D6C3E","html"),
//         array("44656C69766572792D646174","eml"),
//         array("CFAD12FEC5FD746F","dbx"),
//         array("2142444E","pst"),
//         array("D0CF11E0","xls/doc"),
//         array("5374616E64617264204A","mdb"),
//         array("FF575043","wpd"),
//         array("252150532D41646F6265","eps/ps"),
//         array("255044462D312E","pdf"),
//         array("E3828596","pwl"),
//         array("504B0304","zip"),
//         array("52617221","rar"),
//         array("57415645","wav"),
//         array("41564920","avi"),
//         array("2E7261FD","ram"),
//         array("2E524D46","rm"),
//         array("000001BA","mpg"),
//         array("000001B3","mpg"),
//         array("6D6F6F76","mov"),
//         array("3026B2758E66CF11","asf"),
//         array("4D546864","mid"),
//         array("D3C3BBA7", 'csv')
    );
   
    foreach ($array as $v)
    {
        $blen = strlen(pack("H*", $v[0])); //得到文件头标记字节数
        $tbin = substr($bin, 0, intval($blen)); ///需要比较文件头长度
        if(strtolower($v[0]) == strtolower(array_shift(unpack("H*", $tbin))))
        {
            $flag = $v[1];
            break;
        }
    }
    return $flag;
}

?>

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324029828&siteId=291194637