Home Backend Development PHP Tutorial PHP code to detect file type based on file header information

PHP code to detect file type based on file header information

Jul 25, 2016 am 09:00 AM

  1. //Detect file type

  2. function checkFileType($fileName){
  3. $file = fopen($fileName, "rb");
  4. $bin = fread($file , 2); //Only read 2 bytes
  5. fclose($file);
  6. // C is an unsigned integer. All those found on the Internet are c, which is a signed integer. This will cause abnormal negative number judgment
  7. $strInfo = @unpack("C2chars", $bin);
  8. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  9. $fileType = '';

  10. < p> switch( $typeCode )
  11. {
  12. case '255216':
  13. return $typeCode. ' : ' .'jpg';
  14. break;
  15. case '7173':
  16. return $typeCode. ' : ' .'gif';
  17. break;
  18. case '13780':
  19. return $typeCode. ' : ' .'png';
  20. break;
  21. case '6677':
  22. return $typeCode. ' : ' .'bmp';
  23. break;
  24. case ' 7790':
  25. return $typeCode. ' : ' .'exe';
  26. break;
  27. case '7784':
  28. return $typeCode. ' : ' .'midi';
  29. break;
  30. case '8297':
  31. return $ typeCode. ' : ' .'rar';
  32. break;
  33. default:
  34. return $typeCode. ' : ' .'Unknown';
  35. break;
  36. }
  37. //return $typeCode;
  38. }

  39. < ;p>$file_name = '11.doc';
  40. echo checkFileType($file_name);
  41. ?>

Copy code

2. Class to verify file type based on php file header information

  1. /*Get the file type through the file name*

  2. *$filename="d:/1.png";echo cFileTypeCheck::getFileType($filename); print :png
  3. */
  4. class cFileTypeCheck
  5. {
  6. private static $_TypeList=array();
  7. private static $CheckClass=null;
  8. private function __construct($filename)
  9. {
  10. self::$_TypeList=$this-> getTypeList();
  11. }
  12. /**
  13. *Processing file type mapping table*
  14. *
  15. * @param string $filename file type
  16. * @return string file type, not found return: other
  17. */
  18. private function _getFileType($filename)
  19. {
  20. $filetype="other";
  21. if(!file_exists($filename)) throw new Exception("no found file!");
  22. $file = @fopen($filename,"rb");
  23. if(!$file) throw new Exception("file refuse!");
  24. $bin = fread($file, 15) ; //Read only 15 bytes. Different file types have different header information.
  25. fclose($file);
  26. $typelist=self::$_TypeList;
  27. foreach ($typelist as $v)
  28. {
  29. $blen=strlen(pack("H*",$v[0])); //Get the number of bytes marked in the file header
  30. $tbin=substr($bin,0,intval($blen)); ///Need to compare the length of the file header
  31. if(strtolower($v[0])==strtolower (array_shift(unpack("H*",$tbin))))
  32. {
  33. return $v[1];
  34. }
  35. }
  36. return $filetype;
  37. }
  38. /**
  39. *Get file header and file type mapping table*
  40. *
  41. * @return array array(array('key',value)...)
  42. */
  43. public function getTypeList()
  44. {
  45. return array(array("FFD8FFE1","jpg"),
  46. array("89504E47","png"),
  47. array("47494638","gif"),
  48. array("49492A00" ,"tif"),
  49. array("424D","bmp"),
  50. array("41433130","dwg"),
  51. array("38425053","psd"),
  52. array("7B5C727466"," rtf"),
  53. array("3C3F786D6C","xml"),
  54. array("68746D6C3E","html"),
  55. array("44656C69766572792D646174","eml"),
  56. array("CFAD12FEC5FD746F","dbx" ),
  57. array("2142444E","pst"),
  58. array("D0CF11E0","xls/doc"),
  59. array("5374616E64617264204A","mdb"),
  60. array("FF575043","wpd" ),
  61. array("252150532D41646F6265","eps/ps"),
  62. array("255044462D312E","pdf"),
  63. array("E3828596","pwl"),
  64. array("504B0304","zip" ),
  65. array("52617221","rar"),
  66. array("57415645","wav"),
  67. array("41564920","avi"),
  68. array("2E7261FD","ram"),
  69. array("2E524D46","rm"),
  70. array("000001BA","mpg"),
  71. array("000001B3","mpg"),
  72. array("6D6F6F76","mov"),
  73. array ("3026B2758E66CF11","asf"),
  74. array("4D546864","mid"));
  75. }
  76. public static function getFileType($filename)
  77. {
  78. if(!self::$CheckClass) self:: $CheckClass=new self($filename);
  79. $class=self::$CheckClass;
  80. return $class->_getFileType($filename);
  81. }
  82. }

  83. $filename= "22.jpg";

  84. echo $filename,"t",cFileTypeCheck::getFileType($filename),"rn";
  85. $filename="11.doc";
  86. echo $filename,"t",cFileTypeCheck:: getFileType($filename),"rn";

  87. //It can also be detected like this

  88. $filename = '22.jpg';
  89. $extname = strtolower(substr($filename, strrpos($ filename, '.') + 1));
  90. echo $extname.'
    ';
  91. $file = @fopen($filename, 'rb');
  92. if ($file)
  93. {
  94. $ str = @fread($file, 0x400); // Read the first 1024 bytes
  95. echo substr($str, 0, 4);
  96. @fclose($file);
  97. }
  98. if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
  99. {
  100. $format = 'mid';
  101. }
  102. elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
  103. {
  104. $format = 'wav';
  105. }
  106. elseif (substr($str ,0, 3) == "/xFF/xD8/xFF")
  107. {
  108. $format = 'jpg' ;
  109. }
  110. elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
  111. {
  112. $format = 'gif';
  113. }
  114. elseif (substr($str ,0 , 8 ) == "/x89/x50/x4E/x47/x0D/x0A/x1A/x0A")
  115. {
  116. $format = 'png';
  117. }
  118. elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
  119. {
  120. $format = 'bmp';
  121. }
  122. elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0 , 3) == 'FWS') && $extname != 'txt')
  123. {
  124. $format = 'swf';
  125. }
  126. elseif (substr($str ,0, 4) == "/xD0/xCF/ x11/xE0")
  127. { // D0CF11E == DOCFILE == Microsoft Office Document
  128. if (substr($str,0x200,4) == "/xEC/xA5/xC1/x00" || $extname == 'doc ')
  129. {
  130. $format = 'doc';
  131. }
  132. elseif (substr($str,0x200,2) == "/x09/x08" || $extname == 'xls')
  133. {
  134. $format = 'xls';
  135. }elseif (substr($str,0x200,4) == "/xFD/xFF/xFF/xFF" || $extname == 'ppt')
  136. {
  137. $format = 'ppt';
  138. }
  139. } elseif (substr($str ,0, 4) == "PK/x03/x04")
  140. {
  141. $format = 'zip';
  142. } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
  143. {
  144. $format = 'rar';
  145. } elseif (substr($str ,0, 4) == "/x25PDF")
  146. {
  147. $format = 'pdf';
  148. } elseif (substr($str ,0, 3) == "/x30/x82/x0A")
  149. {
  150. $format = 'cert';
  151. } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
  152. {
  153. $format = 'chm';
  154. } elseif (substr($str ,0, 4) == "/x2ERMF")
  155. {
  156. $format = 'rm';
  157. } elseif ($extname == 'sql')
  158. {
  159. $format = 'sql';
  160. } elseif ($extname == 'txt')
  161. {
  162. $format = 'txt';
  163. }
  164. echo $format;
  165. ?>

复制代码


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles