Article provides a php tutorial to detect the file type (based on the file header information) Oh, he can according to the user's header file information to confirm the type of file.
<? php
/ * By file name, get the file type *
* @ author chengmo *
* @ copyright cnblog.com/chengmo 2010-10-17
* @ version 0.1
* $ filename = "d: /1.png"; echo cfiletypecheck :: getfiletype ($ filename); Print: png
* /
class cfiletypecheck
{
private static $ _typelist = array ();
private static $ checkclass = null;
private function __construct ($ filename)
{
self :: $ _ typelist = $ this-> gettypelist ();
}
/ **
* Process file type mapping table *
*
* @param string $ filename file type
* @return string file type not found Back: 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); / / Read only 15 bytes of different file types, header information is not the same.
fclose ($ file);
$ typelist = self :: $ _ typelist;
foreach ($ typelist as $ v)
{
$ blen = strlen (pack ("h *", $ v [0])); // Get the header number of bytes in the header
$ tbin = substr ($ bin, 0, intval ($ blen)); /// Need to compare the file header length
if (strtolower ($ v [0]) == strtolower (array_shift (unpack ("h *", $ tbin))))
{
return $ v [1];
}
}
return $ filetype;
}
/ **
* Get the file header and file type mapping *
*
* @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 tutorial 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);
}
}