PHP determines the file type by taking the binary file header

Source: Internet
Author: User
PHP determines the file type by taking the binary file header

  1. /**
  2. * PHP uses 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); // read-only 2 bytes
  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. ?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.