PHP detects file types based on file header _php Tutorial

Source: Internet
Author: User
File signatures are usually in the header of the file, and if you view the file in hexadecimal, you can see some signature information for the file. If you use Uestudio to view a zip-formatted file in 16, the file content header has 4 b 03 04 hex information. In the same way JPG file status has FF D8 ff E0 xx xx 4 A 46 such hexadecimal information, in fact this hexadecimal is to represent some special note.

How does PHP validate file types? Let's look at a simple method:

function Checkfiletype ($fileName) {          $file = fopen ($fileName, "RB");          $bin = Fread ($file, 2); Read-only 2          -byte fclose ($file);  c is an unsigned integer, the net search is C, signed integer, this will produce negative judgment         $strInfo  = @unpack ("C2chars", $bin);         $typeCode = Intval ($strInfo [' chars1 ']. $strInfo [' chars2 ']);          $fileType = ";  Switch ($typeCode) {case ' 255216 ': return $typeCode. ' : ' .' JPG '; Break;case ' 7173 ': return $typeCode. ' : ' .' GIF '; Break;case ' 13780 ': return $typeCode. ' : ' .' PNG '; Break;case ' 6677 ': return $typeCode. ' : ' .' BMP '; Break;case ' 7790 ': return $typeCode. ' : ' .' EXE '; break;case ' 7784 ': return $typeCode. ' : ' .' Midi '; Break;case ' 8297 ': return $typeCode. ' : ' .' RAR '; Break;default:return $typeCode. ' : ' .' Unknown '; break;} return $typeCode;    } $file _name = ' 11.doc '; Echo checkfiletype ($file _name);

Down to provide a class implementation:

/* Get file type by filename * * @author chengmo qq:8292669* * @copyright Http://www.cnblogs.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 (); }/** * Processing file type mapping Relationship table * * * @param string $filename file type * @return string file type, not found returned: other */priv        Ate 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 each different file type, header information is not the same.                 Fclose ($file);        $typelist =self::$_typelist; foreach ($typelist as $v) {$blen =strlen (Pack ("h*", $v [0])),//Get header Tag bytes $tbin =substr ($bin, 0, IntvAl ($blen));                You need to compare the file header length if (strtolower ($v [0]) ==strtolower (Array_shift (Unpack ("h*", $tbin))) {            return $v [1];    }} return $filetype;     }/** * Get file header with file type mapping table * * * @return 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", "PSD"), 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 "), ARRA    Y ("4d546864", "mid")); The public static function Getfiletype ($filename) {if (!self:: $CheckClass)-Self:: $CheckClass =new-Self ($filena        ME);        $class =self:: $CheckClass;    Return $class->_getfiletype ($filename); }} $filename = "22.jpg"; Echo $filename, "T", Cfiletypecheck::getfiletype ($filename), "rn"; $filename = "11.doc"; echo $ FileName, "T", Cfiletypecheck::getfiletype ($filename), "RN";

Or you can detect this:

$filename = ' 22.jpg '; $extname = Strtolower (substr ($filename, Strrpos ($filename, '. ') + 1); Echo $extname. '
'; $file = @fopen ($filename, ' RB '); if ($file) {$str = @fread ($file, 0x400);//Read the first 1024 bytes of Echo substr ($str, 0, 4); @fclose ($file); } if (substr ($str, 0, 4) = = ' MThd ' && $extname! = ' txt ') {$format = ' mid '; } elseif (substr ($str, 0, 4) = = ' RIFF ' && $extname = = ' wav ') {$format = ' wav '; } elseif (substr ($str, 0, 3) = = "/xff/xd8/xff") {$format = ' jpg '; } elseif (substr ($str, 0, 4) = = ' GIF8 ' && $extname! = ' txt ') {$format = ' gif '; } elseif (substr ($str, 0, 8) = = "/x89/x50/x4e/x47/x0d/x0a/x1a/x0a") {$format = ' png '; } elseif (substr ($str, 0, 2) = = ' BM ' && $extname! = ' txt ') {$format = ' bmp '; } ElseIf ((substr ($str, 0, 3) = = ' CWS ' | | substr ($STR, 0, 3) = = ' FWS ') && $extname! = ' txt ') { $format = ' swf '; } ElseIf (substr ($str, 0, 4) = = "/xd0/xcf/x11/xe0") {//d0cf11e = = Docfile = Microsoft Office Document if (substr ($str, 0x200,4) = = "/xec/xa5/xc1/x00" | | $extname = = ' Doc ') {$format = ' doc '; } elseif (substr ($str, 0x200,2) = = "/x09/x08" | | $extname = = ' xls ') {$format = ' xls '; } elseif (substr ($str, 0x200,4) = = "/xfd/xff/xff/xff" | | $extname = = ' ppt ') {$format = ' ppt '; }} elseif (substr ($str, 0, 4) = = "pk/x03/x04") {$format = ' zip '; } elseif (substr ($str, 0, 4) = = ' rar! ' && $extname! = ' txt ') {$format = ' Rar '; } elseif (substr ($str, 0, 4) = = "/x25pdf") {$format = ' pdf '; } elseif (substr ($str, 0, 3) = = "/x30/x82/x0a") {$format = ' cert '; } elseif (substr ($str, 0, 4) = = ' ITSF ' && $extname! = ' txt ') {$FORmat = ' chm '; } elseif (substr ($str, 0, 4) = = "/x2ermf") {$format = ' rm '; } elseif ($extname = = ' sql ') {$format = ' sql '; } elseif ($extname = = ' txt ') {$format = ' txt '; }echo $format;

http://www.bkjia.com/PHPjc/752375.html www.bkjia.com true http://www.bkjia.com/PHPjc/752375.html techarticle file signatures are usually in the header of the file, and if you view the file in hexadecimal, you can see some signature information for the file. If you are using Uestudio to view the zip grid in 16 binary mode ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.