PHP文件类型判断

function fileType($filename) {
// 读取文件的前4个字节,根据硬编码判断
$file = fopen ( $filename, "rb" );
$strFile = fread ( $file, 4 ); //只读文件头4字节
fclose ( $file );
$strInfo = @unpack ( "C4chars", $strFile );
//dechex(),把十进制转换为十六进制。
$code = dechex ( $strInfo ['chars1'] ) .
dechex ( $strInfo ['chars2'] ) .
dechex ( $strInfo ['chars3'] ) .
dechex ( $strInfo ['chars4'] );
$type = '';
switch ($code) //硬编码值查表
{
case "504b34" :
$type = 'application/zip; charset=binary';
break;
case "89504e47" :
$type = 'image/png; charset=binary';
break;
default :
$type = false;
break;
}
return $type;

衫小寨 出品