PHP detection of file type functions

Source: Internet
Author: User
Tags fread
  1. Detecting file types
  2. by http://bbs.it-home.org
  3. function Checkfiletype ($filename) {
  4. File header
  5. $_typecode = Array (
  6. ' 3780 ',//pdf
  7. ' 8075 ',//.docx,.xlsx,.pptx,.potx,.vsdx,.odt
  8. ' 208207 ',//.doc,.xls,.ppt,.vsd,.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, the net search is C, signed integer, this will produce negative judgment is not normal
  16. $typeCode = Intval ($strInfo [' chars1 ']. $strInfo [' chars2 ']);
  17. EXEC ("File $filename", $output, $return _var);//Use Linux system command file to determine the type of upload file, mainly to determine the Txt,rtf file type
  18. $pattern = '/text,/';//rtf and TXT documents will be detected as text with file detection
  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. ?>
Copy Code
  • Related Article

    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.