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

php+shell检测文件类型

程序员文章站 2022-03-09 12:30:43
...
通过判断 限制上传文件的格式为 PDF,docx,xlsx,pptx,potx,vsdx,odt,doc,xls,ppt,vsd,pot,wps,dps,et和txt,rtf文件类型

希望大家多提意见!
  1. function checkFileType($filename){
  2. //文件头
  3. $_typecode = array(
  4. '3780',//PDF
  5. '8075',//.docx,.xlsx,.pptx,.potx,.vsdx,.odt
  6. '208207',//.doc,.xls,.ppt,.vsd,.pot,.wps,.dps,.et
  7. );
  8. $file = fopen($filename, "rb");
  9. //contents = stream_get_contents($file);
  10. //$contents = fread($file, filesize($filename));
  11. $bin = fread($file, 2); //只读2字节
  12. fclose($file);
  13. $strInfo = @unpack("C2chars", $bin);// C为无符号整数,网上搜到的都是c,为有符号整数,这样会产生负数判断不正常
  14. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  15. exec("file $filename",$output,$return_var);//用linux系统命令file判断上传文件的类型,主要是判断txt,rtf文件类型
  16. $pattern = '/text,/';//rtf和txt文档用file检测都会被检测为text
  17. $_count = preg_match($pattern,strrchr($output[0],":"));
  18. echo $typeCode;
  19. if(in_array($typeCode,$_typecode) || $_count == 1) {
  20. return true;
  21. }else{
  22. return false;
  23. }
  24. }
复制代码