PHP取二进制文件头快速判断文件类型的实现代码
下面代码就展示了自己通过读取文件头信息来识别文件的真实类型。
复制代码 代码如下:
$files = array(
'c:\1.jpg',
'c:\1.png',
'c:\1.gif',
'c:\1.rar',
'c:\1.zip',
'c:\1.exe',
);
foreach ($files AS $file) {
$fp = fopen($file, "rb");
$bin = fread($fp, 2); //只读2字节
fclose($fp);
$str_info = @unpack("C2chars", $bin);
$type_code = intval($str_info['chars1'].$str_info['chars2']);
$file_type = '';
switch ($type_code) {
case 7790:
$file_type = 'exe';
break;
case 7784:
$file_type = 'midi';
break;
case 8075:
$file_type = 'zip';
break;
case 8297:
$file_type = 'rar';
break;
case 255216:
$file_type = 'jpg';
break;
case 7173:
$file_type = 'gif';
break;
case 6677:
$file_type = 'bmp';
break;
case 13780:
$file_type = 'png';
break;
default:
$file_type = 'unknown';
break;
}
echo $file , ' type: ', $file_type, ' code:', $type_code, '
';
}
本例输出结果
c:\1.jpg type: jpg code:255216
c:\1.png type: png code:13780
c:\1.gif type: gif code:7173
c:\1.rar type: rar code:8297
c:\1.zip type: zip code:8075
c:\1.exe type: exe code:7790