php 檢測檔案類型的函數

來源:互聯網
上載者:User
  1. //檢測檔案類型
  2. //by http://bbs.it-home.org
  3. function checkFileType($filename){
  4. //檔案頭
  5. $_typecode = array(
  6. '3780',//PDF
  7. '8075',//.docx,.xlsx,.pptx,.potx,.vsdx,.odt
  8. '208207',//.doc,.xls,.ppt,.vsd,.pot,.wps,.dps,.et
  9. );
  10. $file = fopen($filename, "rb");
  11. //contents = stream_get_contents($file);
  12. //$contents = fread($file, filesize($filename));
  13. $bin = fread($file, 2); //唯讀2位元組
  14. fclose($file);
  15. $strInfo = @unpack("C2chars", $bin);// C為不帶正負號的整數,網上搜到的都是c,為有符號整數,這樣會產生負數判斷不正常
  16. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  17. exec("file $filename",$output,$return_var);//用linux系統命令file判斷上傳檔案的類型,主要是判斷txt,rtf檔案類型
  18. $pattern = '/text,/';//rtf和txt文檔用file檢測都會被檢測為text
  19. $_count = preg_match($pattern,strrchr($output[0],":"));
  20. echo $typeCode;
  21. if(in_array($typeCode,$_typecode) || $_count == 1) {
  22. return true;
  23. }else{
  24. return false;
  25. }
  26. }
  27. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.