Check Mime Type (上傳檔案檢查)


  1. 上傳時應檢查副檔名,最基本的檢查
  2. 上傳後應對檔名進行重新命名,而且加入亂數
  3. 對檔案存放所在的目錄,除去所有相關程式的執行權
  4. 檔案和主程式伺服器最後獨立,那就不怕存在偷 Script 情況,即 (File Server + Main Web Server)
  5. 不要隨意打開用戶所上傳的檔..(大魚!?)..

$_FILES[‘userfile’][‘type’]
The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.

mime_content_type (PHP 4 >= 4.3.0, PHP 5)

1
2
3
<?php
echo mime_content_type(dirname(__FILE__).'\\'."pietty.exe.jpg");
?>

fileinfo (PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

1
2
3
4
5
6
7
8
9
10
11
12
<?php
//方法 1
$info = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $fileName)
echo finfo_file($info, dirname(__FILE__).'\\'.$fileName),"<br />";
finfo_close($info);

// 方法 2
$info = new finfo(FILEINFO_MIME_TYPE);
foreach (glob("*") as $fileName)
echo $info->file(dirname(__FILE__).'\\'.$fileName),"<br />";
?>

至於那種方法好,個人喜好
(任何事都是靠累積,這就是所謂既經驗, 前人種樹後人乘涼)