欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

强大的文件类型检测函数 php代码

程序员文章站 2022-03-16 13:30:18
...
  1. /**
  2. * @access public
  3. * @param string filename 文件名
  4. * @param string limit_ext_types 允许的文件类型,用|包围的类型如:|gif|txt|
  5. * @return string
  6. * by http://bbs.it-home.org
  7. */
  8. function check_file_type($filename, $limit_ext_types = ''){
  9. $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
  10. if ($limit_ext_types &&
  11. stristr($limit_ext_types, '|' . $extname . '|') === false){
  12. return '';
  13. }
  14. $str = $format = '';
  15. $file = @fopen($filename, 'rb');
  16. if ($file){
  17. $str = @fread($file, 0x400); // 读取前 1024 个字节
  18. @fclose($file);
  19. }
  20. else{
  21. $format=$extname;
  22. }
  23. if ($format == '' && strlen($str) >= 2 ){
  24. if (substr($str, 0, 4) == 'MThd' && $extname != 'txt'){
  25. $format = 'mid';
  26. }
  27. elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav'){
  28. $format = 'wav';
  29. }
  30. elseif (substr($str ,0, 3) == "xFFxD8xFF"){
  31. $format = 'jpg';
  32. }
  33. elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt'){
  34. $format = 'gif';
  35. }
  36. elseif (substr($str ,0, 8) == "x89x50x4Ex47x0Dx0Ax1Ax0A"){
  37. $format = 'png';
  38. }
  39. elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt'){
  40. $format = 'bmp';
  41. }
  42. elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS')
  43. && $extname != 'txt'){
  44. $format = 'swf';
  45. }
  46. elseif (substr($str ,0, 4) == "xD0xCFx11xE0"){ // D0CF11E == DOCFILE == Microsoft Office Document
  47. if (substr($str,0x200,4) == "xECxA5xC1x00"
  48. || $extname == 'doc'){
  49. $format = 'doc';
  50. }
  51. elseif (substr($str,0x200,2) == "x09x08" || $extname == 'xls'){
  52. $format = 'xls';
  53. }
  54. elseif (substr($str,0x200,4) == "xFDxFFxFFxFF"
  55. || $extname == 'ppt'){
  56. $format = 'ppt';
  57. }
  58. }
  59. elseif (substr($str ,0, 4) == "PKx03x04"){
  60. $format = 'zip';
  61. }
  62. elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt'){
  63. $format = 'rar';
  64. }
  65. elseif (substr($str ,0, 4) == "x25PDF"){
  66. $format = 'pdf';
  67. }
  68. elseif (substr($str ,0, 3) == "x30x82x0A"){
  69. $format = 'cert';
  70. }
  71. elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt'){
  72. $format = 'chm';
  73. }
  74. elseif (substr($str ,0, 4) == "x2ERMF"){
  75. $format = 'rm';
  76. }
  77. elseif ($extname == 'sql'){
  78. $format = 'sql';
  79. }
  80. elseif ($extname == 'txt'){
  81. $format = 'txt';
  82. }
  83. }
  84. if ($limit_ext_types &&
  85. stristr($limit_ext_types, '|' . $format . '|') === false){
  86. $format = '';
  87. }
  88. return $format;
  89. }
复制代码