Home > Backend Development > PHP Tutorial > A piece of php code that detects the file type (based on the file header)

A piece of php code that detects the file type (based on the file header)

WBOY
Release: 2016-07-25 09:00:46
Original
990 people have browsed it
  1. //Detect file type

  2. $filename = "11.jpg";
  3. //Picture path

  4. $file = fopen ($filename, "rb");

  5. $bin = fread($file, 2); //Read only 2 bytes
  6. fclose($file);

  7. $strInfo = @unpack ("C2chars", $bin);

  8. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  9. $fileType = '';

  10. switch ($typeCode) {

  11. case 7790: $fileType = 'exe'; break;
  12. case 7784: $fileType = 'midi'; break;
  13. case 8297: $fileType = 'rar'; break;
  14. case 255216: $fileType = 'jpg'; break;
  15. case 7173: $fileType = 'gif'; break;
  16. case 6677: $fileType = 'bmp'; break;
  17. case 13780: $fileType = 'png'; break;
  18. default: echo 'unknown';
  19. }

  20. echo'This is a '.$fileType.' file:'.$typeCode;

  21. //Judge file under linux Type function mime_content_type

  22. //This function is also good
  23. echo mime_content_type('test1.gif') . "n";
  24. echo mime_content_type('test2.php');
  25. ?>

Copy code


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