PHP取二进制文件头快速判断文件类型
[php]
<?php
/*文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01 accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*/
/*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: <b>’, $file_type, ‘</b> code:<b>’, $type_code, ‘</b><br />’;
}
[/php]
我建立一个图片数据库,其中有些图片原是GIF,被修改为JPG后缀。手工不好筛选,就找到你这儿,正好解决我的问题。非常感谢!!!