Heim  >  Artikel  >  Backend-Entwicklung  >  php+shell检测文件类型

php+shell检测文件类型

WBOY
WBOYOriginal
2016-07-25 09:01:361085Durchsuche
通过判断 限制上传文件的格式为 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. }
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn