PHP takes binary file header to determine file type

WBOY
Release: 2016-07-25 08:54:08
Original
1033 people have browsed it
  1. /**
  2. * PHP takes the binary file header to quickly determine the file type
  3. *
  4. * @param file $file
  5. * @return string
  6. * @author lrenwang
  7. * @blog blog.lrenwang.com
  8. */
  9. function get_extname($file)
  10. {
  11. $fp = fopen($file, "rb");
  12. $bin = fread($fp, 2); //只读2字节
  13. fclose($fp);
  14. $bin_info = @unpack("C2chars", $bin);
  15. $code = intval($bin_info['chars1'].$bin_info['chars2']);
  16. switch ($code) {
  17. case 7790:
  18. $type = 'exe';
  19. break;
  20. case 7784:
  21. $type = 'midi';
  22. break;
  23. case 8075:
  24. $type = 'zip';
  25. break;
  26. case 8297:
  27. $type = 'rar';
  28. break;
  29. case 255216:
  30. $type = 'jpg';
  31. break;
  32. case 7173:
  33. $type = 'gif';
  34. break;
  35. case 6677:
  36. $type = 'bmp';
  37. break;
  38. case 13780:
  39. $type = 'png';
  40. break;
  41. default:
  42. $type = $code;
  43. break;
  44. }
  45. return $type;
  46. }
  47. ?>
复制代码


source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template