Sample code for php to detect uploaded excel file type

WBOY
Release: 2016-07-25 08:55:38
Original
1305 people have browsed it
  1. /**
  2. * Detect upload file type
  3. * Detect the excel file type of the uploaded file
  4. * @param array $file
  5. * @return bool $flag
  6. * @site bbs.it-home.org
  7. */
  8. private function detectUploadFileMIME($file) {
  9. // 1.through the file extension judgement 03 or 07
  10. $flag = 0;
  11. $file_array = explode ( ".", $file ["name"] );
  12. $file_extension = strtolower ( array_pop ( $file_array ) );
  13. // 2.through the binary content to detect the file
  14. switch ($file_extension) {
  15. case "xls" :
  16. // 2003 excel
  17. $fh = fopen ( $file ["tmp_name"], "rb" );
  18. $bin = fread ( $fh, 8 );
  19. fclose ( $fh );
  20. $strinfo = @unpack ( "C8chars", $bin );
  21. $typecode = "";
  22. foreach ( $strinfo as $num ) {
  23. $typecode .= dechex ( $num );
  24. }
  25. if ($typecode == "d0cf11e0a1b11ae1") {
  26. $flag = 1;
  27. }
  28. break;
  29. case "xlsx" :
  30. // 2007 excel
  31. $fh = fopen ( $file ["tmp_name"], "rb" );
  32. $bin = fread ( $fh, 4 );
  33. fclose ( $fh );
  34. $strinfo = @unpack ( "C4chars", $bin );
  35. $typecode = "";
  36. foreach ( $strinfo as $num ) {
  37. $typecode .= dechex ( $num );
  38. }
  39. echo $typecode;
  40. if ($typecode == "504b34") {
  41. $flag = 1;
  42. }
  43. break;
  44. }
  45. // 3.return the flag
  46. return $flag;
  47. }
复制代码


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