欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php检测上传excel文件类型的示例代码

程序员文章站 2022-05-01 13:29:48
...
  1. /**
  2. * Detect upload file type
  3. * 检测上传文件的excel文件类型
  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. }
复制代码