php實現(xiàn)不通過擴展名準確判斷文件類型的方法【finfo_file方法與二進制流】
本文實例講述了php實現(xiàn)不通過擴展名準確判斷文件類型的方法。分享給大家供大家參考,具體如下:
第一種方法
通過php的finfo_file()
$handle=finfo_open(FILEINFO_MIME_TYPE);//This function opens a magic database and returns its resource. $fileInfo=finfo_file($handle,'./test.txt');// Return information about a file finfo_close($handle); print_r($fileInfo); echo '==========="\n"';
另外
finfo_buffer: Return information about a string buffer
finfo_close: Close fileinfo resource
mime_content_type:Detect MIME Content-type for a file (deprecated)
第二種方法
通過二進制流獲取文件內(nèi)容
$fp=fopen('test.txt','r')///實際是image/png
$bin = fread($fp, 2); //只讀2字節(jié)
fclose($fp);
$str_info = @unpack(“C2chars”, $bin);//Unpack data from binary string
$type_code = intval($str_info['chars1'].$str_info['chars2']);// Get the integer value of a variable
$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;
}
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php文件操作總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP加密函數(shù) Javascript/Js 解密函數(shù)
php加密,js解密,貌似沒什么意義,主要是key在js中會被看到,不過在某些地方可能會用到2013-09-09
PHP獲取表單textarea數(shù)據(jù)中的換行問題
閑來無事,在網(wǎng)上看到一篇關(guān)于php表單轉(zhuǎn)換textarea換行符的文章,看完后,根據(jù)以往經(jīng)驗,感覺上這篇文章中的一些信息并不準確...于是便自己親自對php獲取表單數(shù)據(jù)中的換行符問題進行研究2010-09-09
工廠模式在Zend Framework中應(yīng)用介紹
在Zend Framework中,使用了多種設(shè)計模式。其中對數(shù)據(jù)庫的封裝,用到了工廠模式2012-07-07
在WordPress中使用wp_count_posts函數(shù)來統(tǒng)計文章數(shù)量
這篇文章主要介紹了在WordPress中使用wp_count_posts函數(shù)來統(tǒng)計文章數(shù)量的方法,同時也可以統(tǒng)計草稿及頁面的數(shù)量,相當實用,需要的朋友可以參考下2016-01-01

