php+shell檢測檔案類型

來源:互聯網
上載者:User
通過判斷 限制上傳檔案的格式為 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. }
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.