强大的php检查文件类型

一个强大的文件类型检测函数,它可以判断你上传的文件是什么类型,利用这个函数使用文件的类型没有办法伪装过去,代码如下:

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