Home  >  Article  >  Backend Development  >  An example of code to determine uploaded file type in PHP

An example of code to determine uploaded file type in PHP

WBOY
WBOYOriginal
2016-07-25 08:59:41997browse
  1. /**
  2. * Determine uploaded file type
  3. * Edit bbs.it-home.org
  4. */
  5. function file_type($filename)
  6. {
  7. $file = fopen($filename, "rb");
  8. $bin = fread($file, 2); //只读2字节
  9. fclose($file);
  10. $strInfo = @unpack("C2chars", $bin);
  11. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  12. $fileType = '';
  13. switch ($typeCode)
  14. {
  15. case 7790:
  16. $fileType = 'exe';
  17. break;
  18. case 7784:
  19. $fileType = 'midi';
  20. break;
  21. case 8297:
  22. $fileType = 'rar';
  23. break;
  24. case 8075:
  25. $fileType = 'zip';
  26. break;
  27. case 255216:
  28. $fileType = 'jpg';
  29. break;
  30. case 7173:
  31. $fileType = 'gif';
  32. break;
  33. case 6677:
  34. $fileType = 'bmp';
  35. break;
  36. case 13780:
  37. $fileType = 'png';
  38. break;
  39. default:
  40. $fileType = 'unknown: '.$typeCode;
  41. }
  42. //Fix
  43. if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg';
  44. if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';
  45. return $fileType;
  46. }
  47. //调用
  48. echo file_type('start.php'); // 6063 or 6033
  49. ?>
复制代码

不知道反过来定义 6063或者6033 就是指php的话 是不是不够严谨啊。

上面的代码,对于构造假的图片的文件类型判断,不是很好使。 此时可以考虑使用getimagesize来判断,参考代码如下:

  1. /**
  2. * getimagesize determines the file type
  3. * Edit bbs.it-home.org
  4. */
  5. if(in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($target))
  6. {
  7. unlink($target);
  8. upload_error('post_attachment_ext_notallowed', $attacharray);
  9. }
  10. ?>
复制代码


Statement:
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