This article provides a php file detection type (based on the file header information). It can determine the file type based on the file header information published by the user.
This article provides a php tutorial to check the file type (based on the file header information). You can check the file type based on the file header information published by the user.
<? Php
/* Obtain the file type by file name *
* @ 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 the file type ing table *
*
* @ Param string $ filename file type
* @ Return string file type. The returned value is 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 for different file types and different header information.
Fclose ($ file );
$ Typelist = self ::$ _ typelist;
Foreach ($ typelist as $ v)
{
$ Blen = strlen (pack ("h *", $ v [0]); // get the number of bytes marked by the file header
$ Tbin = substr ($ bin, 0, intval ($ blen); // 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 ing table *
*
* @ Return array ('key', value )...)
*/
Public function gettypelist ()
{
Return array ("ffd8ffe1", "jpg "),
Array ("89504e47", "png "),
Array ("47494638", "gif "),
Array ("49347a00", "tif "),
Array ("mongod", "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 ("5374616e64617213204a", "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 ("2e00001fd", "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 );
}
}