当前位置:Gxlcms > PHP教程 > 强大的文件类型检测函数php代码

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

时间:2021-07-01 10:21:17 帮助过:12人阅读

  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. }

人气教程排行