Home  >  Article  >  Backend Development  >  php function to detect file type

php function to detect file type

WBOY
WBOYOriginal
2016-07-25 09:00:481230browse
  1. //Detect file type
  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. All those found on the Internet are c, which is a signed integer. This will cause abnormal judgment of negative numbers
  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 uploaded file, mainly to determine the txt, rtf file type
  18. $pattern = '/text,/';//rtf and txt documents will be detected as text using 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


Statement:
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