php檢測檔案類型(根據檔案header資訊)

來源:互聯網
上載者:User
 代碼如下 複製代碼
<?php
/*通過檔案名稱,獲得檔案類型*
*@author chengmo*
*@copyright cnblog.com/chengmo 2010-10-17
*@version 0.1
*$filename="d:/1.png";echo cfiletypecheck::getfiletype($filename); 列印:png
*/
class cfiletypecheck
{
private static $_typelist=array();
private static $checkclass=null;
private function __construct($filename)
{
self::$_typelist=$this->gettypelist();
}
/**
*處理檔案類型映射關係表*
*
* @param string $filename 檔案類型
* @return string 檔案類型,沒有找到返回:other
*/
private function _getfiletype($filename)
{
$filetype="other";
if(!file_exists($filename)) throw new exception("no found file!");
$file = @fopen($filename,"rb");
if(!$file) throw new exception("file refuse!");
$bin = fread($file, 15); //唯讀15位元組 各個不同檔案類型,頭資訊不一樣。
fclose($file);
$typelist=self::$_typelist;
foreach ($typelist as $v)
{
$blen=strlen(pack("h*",$v[0])); //得到檔案頭標記位元組數
$tbin=substr($bin,0,intval($blen)); ///需要比較檔案頭長度
if(strtolower($v[0])==strtolower(array_shift(unpack("h*",$tbin))))
{
return $v[1];
}
}
return $filetype;
}
/**
*得到檔案頭與檔案類型映射表*
*
* @return array array(array('key',value)...)
*/
public function gettypelist()
{
return array(array("ffd8ffe1","jpg"),
array("89504e47","png"),
array("47494638","gif"),
array("49492a00","tif"),
array("424d","bmp"),
array("41433130","dwg"),
array("38425053","ps教程d"),
array("7b5c727466","rtf"),
array("3c3f786d6c","xml"),
array("68746d6c3e","html"),
array("44656c69766572792d646174","eml"),
array("cfad12fec5fd746f","dbx"),
array("2142444e","pst"),
array("d0cf11e0","xls/doc"),
array("5374616e64617264204a","mdb"),
array("ff575043","wpd"),
array("252150532d41646f6265","eps/ps"),
array("255044462d312e","pdf"),
array("e3828596","pwl"),
array("504b0304","zip"),
array("52617221","rar"),
array("57415645","wav"),
array("41564920","avi"),
array("2e7261fd","ram"),
array("2e524d46","rm"),
array("000001ba","mpg"),
array("000001b3","mpg"),
array("6d6f6f76","mov"),
array("3026b2758e66cf11","asf"),
array("4d546864","mid"));
}
public static function getfiletype($filename)
{
if(!self::$checkclass) self::$checkclass=new self($filename);
$class=self::$checkclass;
return $class->_getfiletype($filename);
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.