我从网上找了一些代码: function check_file_type($filename) { $file = fopen($filename, "rb"); $bin = fread($file, 2); //只读2字节 fclose($file); $strInfo = @unpack("C2chars", $bin); $typeCode = intval($strInfo['chars1'].$strInfo['chars2']); $fileType = ''; switch ($typeCode) { case 7790: $fileType = 'exe'; break; case 7784: $fileType = 'midi'; break; case 8297: $fileType = 'rar'; break; case 8075: $fileType = 'zip'; break; case 255216: $fileType = 'jpg'; break; case 7173: $fileType = 'gif'; break; case 6677: $fileType = 'bmp'; break; case 13780: $fileType = 'png'; break; default: $fileType = 'unknown: '.$typeCode; }
//Fix if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg'; if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';
判断类型是否在你需要的范围中,你限定的类型可以用数组
例如
$array=('xxx','yyy');//xxx yyy为你需要限制的类型
if(!in_array($type,$array))
return false;
function check_file_type($filename)
{
$file = fopen($filename, "rb");
$bin = fread($file, 2); //只读2字节
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
switch ($typeCode)
{
case 7790:
$fileType = 'exe';
break;
case 7784:
$fileType = 'midi';
break;
case 8297:
$fileType = 'rar';
break;
case 8075:
$fileType = 'zip';
break;
case 255216:
$fileType = 'jpg';
break;
case 7173:
$fileType = 'gif';
break;
case 6677:
$fileType = 'bmp';
break;
case 13780:
$fileType = 'png';
break;
default:
$fileType = 'unknown: '.$typeCode;
}
//Fix
if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg';
if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';
return $fileType;
}用它判断严不严谨
况且浏览器都不能正确判断所有的图片类型
同一个文件通过不同的浏览器上传,就可能有不同的结果