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. <p><?php
  2. //Detect file type
  3. function checkFileType($fileName){
  4. $file = fopen($fileName, "rb");
  5. $bin = fread($file , 2); //Only read 2 bytes
  6. fclose($file);
  7. // 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
  8. $strInfo = @unpack("C2chars", $bin);
  9. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  10. $fileType = ''; </p>
  11. < p> switch( $typeCode )
  12. {
  13. case '255216':
  14. return $typeCode. ' : ' .'jpg';
  15. break;
  16. case '7173':
  17. return $typeCode. ' : ' .'gif';
  18. break;
  19. case '13780':
  20. return $typeCode. ' : ' .'png';
  21. break;
  22. case '6677':
  23. return $typeCode. ' : ' .'bmp';
  24. break;
  25. case ' 7790':
  26. return $typeCode. ' : ' .'exe';
  27. break;
  28. case '7784':
  29. return $typeCode. ' : ' .'midi';
  30. break;
  31. case '8297':
  32. return $ typeCode. ' : ' .'rar';
  33. break;
  34. default:
  35. return $typeCode. ' : ' .'Unknown';
  36. break;
  37. }
  38. //return $typeCode;
  39. }</p>
  40. &lt ;p>$file_name = '11.doc';
  41. echo checkFileType($file_name);
  42. ?></p>
Copy code

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

  1. <p><?php
  2. /*Get the file type through the file name*
  3. *$filename="d:/1.png";echo cFileTypeCheck::getFileType($filename); print :png
  4. */
  5. class cFileTypeCheck
  6. {
  7. private static $_TypeList=array();
  8. private static $CheckClass=null;
  9. private function __construct($filename)
  10. {
  11. self::$_TypeList=$this-> getTypeList();
  12. }
  13. /**
  14. *Processing file type mapping table*
  15. *
  16. * @param string $filename file type
  17. * @return string file type, not found return: other
  18. */
  19. private function _getFileType($filename)
  20. {
  21. $filetype="other";
  22. if(!file_exists($filename)) throw new Exception("no found file!");
  23. $file = @fopen($filename,"rb");
  24. if(!$file) throw new Exception("file refuse!");
  25. $bin = fread($file, 15) ; //Read only 15 bytes. Different file types have different header information.
  26. fclose($file);
  27. $typelist=self::$_TypeList;
  28. foreach ($typelist as $v)
  29. {
  30. $blen=strlen(pack("H*",$v[0])); //Get the number of bytes marked in the file header
  31. $tbin=substr($bin,0,intval($blen)); ///Need to compare the length of the file header
  32. if(strtolower($v[0])==strtolower (array_shift(unpack("H*",$tbin))))
  33. {
  34. return $v[1];
  35. }
  36. }
  37. return $filetype;
  38. }
  39. /**
  40. *Get file header and file type mapping table*
  41. *
  42. * @return array array(array('key',value)...)
  43. */
  44. public function getTypeList()
  45. {
  46. return array(array("FFD8FFE1","jpg"),
  47. array("89504E47","png"),
  48. array("47494638","gif"),
  49. array("49492A00" ,"tif"),
  50. array("424D","bmp"),
  51. array("41433130","dwg"),
  52. array("38425053","psd"),
  53. array("7B5C727466"," rtf"),
  54. array("3C3F786D6C","xml"),
  55. array("68746D6C3E","html"),
  56. array("44656C69766572792D646174","eml"),
  57. array("CFAD12FEC5FD746F","dbx" ),
  58. array("2142444E","pst"),
  59. array("D0CF11E0","xls/doc"),
  60. array("5374616E64617264204A","mdb"),
  61. array("FF575043","wpd" ),
  62. array("252150532D41646F6265","eps/ps"),
  63. array("255044462D312E","pdf"),
  64. array("E3828596","pwl"),
  65. array("504B0304","zip" ),
  66. array("52617221","rar"),
  67. array("57415645","wav"),
  68. array("41564920","avi"),
  69. array("2E7261FD","ram"),
  70. array("2E524D46","rm"),
  71. array("000001BA","mpg"),
  72. array("000001B3","mpg"),
  73. array("6D6F6F76","mov"),
  74. array ("3026B2758E66CF11","asf"),
  75. array("4D546864","mid"));
  76. }
  77. public static function getFileType($filename)
  78. {
  79. if(!self::$CheckClass) self:: $CheckClass=new self($filename);
  80. $class=self::$CheckClass;
  81. return $class->_getFileType($filename);
  82. }
  83. }</p>
  84. <p>$filename= "22.jpg";
  85. echo $filename,"t",cFileTypeCheck::getFileType($filename),"rn";
  86. $filename="11.doc";
  87. echo $filename,"t",cFileTypeCheck:: getFileType($filename),"rn";</p>
  88. <p>//It can also be detected like this
  89. $filename = '22.jpg';
  90. $extname = strtolower(substr($filename, strrpos($ filename, '.') + 1));
  91. echo $extname.'<br />';
  92. $file = @fopen($filename, 'rb');
  93. if ($file)
  94. {
  95. $ str = @fread($file, 0x400); // Read the first 1024 bytes
  96. echo substr($str, 0, 4);
  97. @fclose($file);
  98. }
  99. if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
  100. {
  101. $format = 'mid';
  102. }
  103. elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
  104. {
  105. $format = 'wav';
  106. }
  107. elseif (substr($str ,0, 3) == "/xFF/xD8/xFF")
  108. {
  109. $format = 'jpg' ;
  110. }
  111. elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
  112. {
  113. $format = 'gif';
  114. }
  115. elseif (substr($str ,0 , 8 ) == "/x89/x50/x4E/x47/x0D/x0A/x1A/x0A")
  116. {
  117. $format = 'png';
  118. }
  119. elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
  120. {
  121. $format = 'bmp';
  122. }
  123. elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0 , 3) == 'FWS') && $extname != 'txt')
  124. {
  125. $format = 'swf';
  126. }
  127. elseif (substr($str ,0, 4) == "/xD0/xCF/ x11/xE0")
  128. { // D0CF11E == DOCFILE == Microsoft Office Document
  129. if (substr($str,0x200,4) == "/xEC/xA5/xC1/x00" || $extname == 'doc ')
  130. {
  131. $format = 'doc';
  132. }
  133. elseif (substr($str,0x200,2) == "/x09/x08" || $extname == 'xls')
  134. {
  135. $format = 'xls';
  136. }elseif (substr($str,0x200,4) == "/xFD/xFF/xFF/xFF" || $extname == 'ppt')
  137. {
  138. $format = 'ppt';
  139. }
  140. } elseif (substr($str ,0, 4) == "PK/x03/x04")
  141. {
  142. $format = 'zip';
  143. } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
  144. {
  145. $format = 'rar';
  146. } elseif (substr($str ,0, 4) == "/x25PDF")
  147. {
  148. $format = 'pdf';
  149. } elseif (substr($str ,0, 3) == "/x30/x82/x0A")
  150. {
  151. $format = 'cert';
  152. } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
  153. {
  154. $format = 'chm';
  155. } elseif (substr($str ,0, 4) == "/x2ERMF")
  156. {
  157. $format = 'rm';
  158. } elseif ($extname == 'sql')
  159. {
  160. $format = 'sql';
  161. } elseif ($extname == 'txt')
  162. {
  163. $format = 'txt';
  164. }
  165. echo $format;
  166. ?></p>
复制代码


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 Article Tags

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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

11 Best PHP URL Shortener Scripts (Free and Premium)

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Introduction to the Instagram API

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

12 Best PHP Chat Scripts on CodeCanyon

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

Notifications in Laravel

See all articles