PHP判斷上傳文件類型的解決辦法
更新時間:2015年10月20日 14:08:02 投稿:lijiao
php通過判斷上傳文件的頭字符來判斷文件的類型,這可以稱得上是最安全,最真實(shí)確定上傳文件類型的方法了,具體實(shí)現(xiàn)方法如下
分享給大家php判斷上傳文件類型的方法,大家一起學(xué)習(xí)學(xué)習(xí)。
/**
* 讀取文件前幾個字節(jié) 判斷文件類型
* @return String
*/
function checkTitle($filename){
$file=fopen($filename, "rb");
$bin=fread($file, 2); //只讀2字節(jié)
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 255216:
$fileType='jpg';
break;
case 7173:
$fileType='gif';
break;
case 6677:
$fileType='bmp';
break;
case 13780:
$fileType='png';
break;
default:
$fileType='unknown'.$typeCode;
break;
}
//Fix
if($strInfo['chars1']=='-1' && $strInfo['chars2']=='-40'){
return 'jpg';
}
if($strInfo['chars1']=='-119' && $strInfo['chars2']=='80'){
return 'png';
}
return $fileType;
}
希望通過本文對大家學(xué)習(xí)php程序設(shè)計有所幫助。
相關(guān)文章
PHP數(shù)組 為文章加關(guān)鍵字連接 文章內(nèi)容自動加鏈接
PHP給文章加關(guān)鍵字連接,像163文章內(nèi)容自動加鏈接效果,其實(shí)很多php網(wǎng)站管理系統(tǒng)里面都有,可以參考里面的代碼。2011-12-12
解決File size limit exceeded 錯誤的方法
本篇文章是對File size limit exceeded 錯誤進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06

