php判斷上傳檔案類型的代碼一例

來源:互聯網
上載者:User
  1. /**
  2. * 判斷上傳檔案類型
  3. * Edit bbs.it-home.org
  4. */
  5. function file_type($filename)
  6. {
  7. $file = fopen($filename, "rb");
  8. $bin = fread($file, 2); //唯讀2位元組
  9. fclose($file);
  10. $strInfo = @unpack("C2chars", $bin);
  11. $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
  12. $fileType = '';
  13. switch ($typeCode)
  14. {
  15. case 7790:
  16. $fileType = 'exe';
  17. break;
  18. case 7784:
  19. $fileType = 'midi';
  20. break;
  21. case 8297:
  22. $fileType = 'rar';
  23. break;
  24. case 8075:
  25. $fileType = 'zip';
  26. break;
  27. case 255216:
  28. $fileType = 'jpg';
  29. break;
  30. case 7173:
  31. $fileType = 'gif';
  32. break;
  33. case 6677:
  34. $fileType = 'bmp';
  35. break;
  36. case 13780:
  37. $fileType = 'png';
  38. break;
  39. default:
  40. $fileType = 'unknown: '.$typeCode;
  41. }
  42. //Fix
  43. if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg';
  44. if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';
  45. return $fileType;
  46. }
  47. //調用
  48. echo file_type('start.php'); // 6063 or 6033
  49. ?>
複製代碼

不知道反過來定義 6063或者6033 就是指php的話 是不是不夠嚴謹啊。

上面的代碼,對於構造假的圖片的檔案類型判斷,不是很好使。此時可以考慮使用getimagesize來判斷,參考代碼如下:

  1. /**
  2. * getimagesize判斷檔案類型
  3. * Edit bbs.it-home.org
  4. */
  5. if(in_array($attach['ext'], array('jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp')) && function_exists('getimagesize') && !@getimagesize($target))
  6. {
  7. unlink($target);
  8. upload_error('post_attachment_ext_notallowed', $attacharray);
  9. }
  10. ?>
複製代碼
  • 聯繫我們

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