一個強大的文件類型檢測函數,它可以判斷你上傳的文件是什麼類型,這個你沒有辦法為裝過去的,有需要的朋友可以參考一下。
代碼如下
復制代碼
**
*
*
* @access public
* @param string filename 文件名
* @param string limit_ext_types 允許的文件類型,用|包圍的類型如:|gif|txt|
* @return string
*/<span id="more-472"></span>
function check_file_type($filename, $limit_ext_types = ''){
$extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
if ($limit_ext_types &&
stristr($limit_ext_types, '|' . $extname . '|') === false){
return '';
}
$str = $format = '';
$file = @fopen($filename, 'rb');
if ($file){
$str = @fread($file, 0x400); // 讀取前 1024 個字節
@fclose($file);
}
else{
$format=$extname;
}
if ($format == '' && strlen($str) >= 2 ){
if (substr($str, 0, 4) == 'MThd' && $extname != 'txt'){
$format = 'mid';
}
elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav'){
$format = 'wav';
}
elseif (substr($str ,0, 3) == "xFFxD8xFF"){
$format = 'jpg';
}
elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt'){
$format = 'gif';
}
elseif (substr($str ,0, 8) == "x89x50x4Ex47x0Dx0Ax1Ax0A"){
$format = 'png';
}
elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt'){
$format = 'bmp';
}
elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS')
&& $extname != 'txt'){
$format = 'swf';
}
elseif (substr($str ,0, 4) == "xD0xCFx11xE0"){ // D0CF11E == DOCFILE == Microsoft Office Document
if (substr($str,0x200,4) == "xECxA5xC1x00"
|| $extname == 'doc'){
$format = 'doc';
}
elseif (substr($str,0x200,2) == "x09x08" || $extname == 'xls'){
$format = 'xls';
}
elseif (substr($str,0x200,4) == "xFDxFFxFFxFF"
|| $extname == 'ppt'){
$format = 'ppt';
}
}
elseif (substr($str ,0, 4) == "PKx03x04"){
$format = 'zip';
}
elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt'){
$format = 'rar';
}
elseif (substr($str ,0, 4) == "x25PDF"){
$format = 'pdf';
}
elseif (substr($str ,0, 3) == "x30x82x0A"){
$format = 'cert';
}
elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt'){
$format = 'chm';
}
elseif (substr($str ,0, 4) == "x2ERMF"){
$format = 'rm';
}
elseif ($extname == 'sql'){
$format = 'sql';
}
elseif ($extname == 'txt'){
$format = 'txt';
}
}
if ($limit_ext_types &&
stristr($limit_ext_types, '|' . $format . '|') === false){
$format = '';
}
return $format;
}