Php functions for detecting file types

Source: Internet
Author: User
Php functions for detecting file types

  1. // Check the file type
  2. // By http://bbs.it-home.org
  3. Function checkFileType ($ filename ){
  4. // File header
  5. $ _ Typecode = array (
  6. '000000', // PDF
  7. '123', // .docx,.xlsx,.pptx,. potx,. vsdx,. odt
  8. '20140901', // .doc,.xls,.ppt,. sealing,. pot,. wps,. dps,. et
  9. );
  10. $ File = fopen ($ filename, "rb ");
  11. // Contents = stream_get_contents ($ file );
  12. // $ Contents = fread ($ file, filesize ($ filename ));
  13. $ Bin = fread ($ file, 2); // read-only 2 bytes
  14. Fclose ($ file );
  15. $ StrInfo = @ unpack ("C2chars", $ bin); // C is an unsigned integer. all searched online is c, which is a signed integer. Therefore, negative numbers are generated.
  16. $ TypeCode = intval ($ strInfo ['chars1']. $ strInfo ['chars2']);
  17. Exec ("file $ filename", $ output, $ return_var); // use the linux system command file to determine the type of the uploaded file, mainly to determine the txt and rtf file types
  18. $ Pattern = '/text,/'; // both the rtf and txt files are detected as text
  19. $ _ Count = preg_match ($ pattern, strrchr ($ output [0], ":");
  20. Echo $ typeCode;
  21. If (in_array ($ typeCode, $ _ typecode) | $ _ count = 1 ){
  22. Return true;
  23. } Else {
  24. Return false;
  25. }
  26. }
  27. ?>

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.