雖然使用 finfo_file() 來驗證上傳的圖片檔(檢查假定的圖片檔是否真的包含圖片)看起來很誘人,但結果並不可靠。例如,將有害的可執行程式碼包裝在辨識為 GIF 的檔案中並不困難。
更好且更安全的選項是檢查以下結果:
if (!$img = @imagecreatefromgif($uploadedfilename)) {
trigger_error('這不是 GIF 圖片!',E_USER_WARNING);
// 執行必要的處理
}
(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)
finfo_file -- finfo::file — 傳回檔案資訊
程序式風格
物件導向風格
此函式用於取得檔案的相關資訊。
finfo
一個 finfo 實例,由 finfo_open() 回傳。
filename
要檢查的檔案名稱。
flags
一個或多個 Fileinfo 常數 的聯集 (disjunction)。
context
關於 contexts
的說明,請參考 串流函式。
回傳 filename
參數內容的文字描述,如果發生錯誤則回傳 false
。
範例 #1 finfo_file() 範例
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // 回傳 MIME 類型,也就是 mimetype 副檔名
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
上述範例會輸出類似以下的內容
text/html image/gif application/vnd.ms-excel
雖然使用 finfo_file() 來驗證上傳的圖片檔(檢查假定的圖片檔是否真的包含圖片)看起來很誘人,但結果並不可靠。例如,將有害的可執行程式碼包裝在辨識為 GIF 的檔案中並不困難。
更好且更安全的選項是檢查以下結果:
if (!$img = @imagecreatefromgif($uploadedfilename)) {
trigger_error('這不是 GIF 圖片!',E_USER_WARNING);
// 執行必要的處理
}
如何取得遠端檔案的 MIME 類型的方法。
<?php
class MimeStreamWrapper
{
const WRAPPER_NAME = 'mime';
public $context;
private static $isRegistered = false;
private $callBackFunction;
private $eof = false;
private $fp;
private $path;
private $fileStat;
private function getStat()
{
if ($fStat = fstat($this->fp)) {
return $fStat;
}
$size = 100;
if ($headers = get_headers($this->path, true)) {
$head = array_change_key_case($headers, CASE_LOWER);
$size = (int)$head['content-length'];
}
$blocks = ceil($size / 512);
return array(
'dev' => 16777220,
'ino' => 15764,
'mode' => 33188,
'nlink' => 1,
'uid' => 10000,
'gid' => 80,
'rdev' => 0,
'size' => $size,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 4096,
'blocks' => $blocks,
);
}
public function setPath($path)
{
$this->path = $path;
$this->fp = fopen($this->path, 'rb') or die('Cannot open file: ' . $this->path);
$this->fileStat = $this->getStat();
}
public function read($count) {
return fread($this->fp, $count);
}
public function getStreamPath()
{
return str_replace(array('ftp://', 'http://', 'https://'), self::WRAPPER_NAME . '://', $this->path);
}
public function getContext()
{
if (!self::$isRegistered) {
stream_wrapper_register(self::WRAPPER_NAME, get_class());
self::$isRegistered = true;
}
return stream_context_create(
array(
self::WRAPPER_NAME => array(
'cb' => array($this, 'read'),
'fileStat' => $this->fileStat,
)
)
);
}
public function stream_open($path, $mode, $options, &$opened_path)
{
if (!preg_match('/^r[bt]?$/', $mode) || !$this->context) {
return false;
}
$opt = stream_context_get_options($this->context);
if (!is_array($opt[self::WRAPPER_NAME]) ||
!isset($opt[self::WRAPPER_NAME]['cb']) ||
!is_callable($opt[self::WRAPPER_NAME]['cb'])
) {
return false;
}
$this->callBackFunction = $opt[self::WRAPPER_NAME]['cb'];
$this->fileStat = $opt[self::WRAPPER_NAME]['fileStat'];
return true;
}
public function stream_read($count)
{
if ($this->eof || !$count) {
return '';
}
if (($s = call_user_func($this->callBackFunction, $count)) == '') {
$this->eof = true;
}
return $s;
}
public function stream_eof()
{
return $this->eof;
}
public function stream_stat()
{
return $this->fileStat;
}
public function stream_cast($castAs)
{
$read = null;
$write = null;
$except = null;
return @stream_select($read, $write, $except, $castAs);
}
}
$path = 'http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png';
echo "File: ", $path, "\n";
$wrapper = new MimeStreamWrapper();
$wrapper->setPath($path);
$fInfo = new finfo(FILEINFO_MIME);
echo "MIME-type: ", $fInfo->file($wrapper->getStreamPath(), FILEINFO_MIME_TYPE, $wrapper->getContext()), "\n";
?>
只是要說明一下(因為我遇到了!),目前 finfo_file 的實作有一個已知的錯誤,當文字檔中存在某些字串時,會導致 PHP 分配大量的記憶體。
更多資訊請參見 https://bugs.php.net/bug.php?id=69224。
嗯,我有一個很大的問題,MS Office 2007 的副檔名(pptx、xlsx、docx)沒有預設的 MIME 類型,它們的 MIME 類型是「application/zip」,所以,為了修正這個問題,我寫了一個小函式來驗證副檔名。
這個函式可以讓您免於偽造副檔名的攻擊。
<?php
$arrayZips = array("application/zip", "application/x-zip", "application/x-zip-compressed");
$arrayExtensions = array(".pptx", ".docx", ".dotx", ".xlsx");
$file = 'path/to/file.xlsx';
$original_extension = (false === $pos = strrpos($file, '.')) ? '' : substr($file, $pos);
$finfo = new finfo(FILEINFO_MIME);
$type = $finfo->file($file);
if (in_array($type, $arrayZips) && in_array($original_extension, $arrayExtensions))
{
return $original_extension;
}
?>
我所有檔案都得到 application/octet-stream 或「<= 不支援」。
我發現 PHP 5.3 中的 magic 檔案是內建在 PHP 中的,而且應該使用它。在系統上找到的 magic 檔案可能不總是 libmagic 所期望的,因此會發生錯誤。
Windows 上 finfo_file 的另一個有趣特性。
此函式對於某些檔案類型(例如 ppt)可能會返回空字串而不是 FALSE。因此,為了確保安全,請對輸出結果進行三重檢查,並提供預設類型以防萬一。以下是一個範例程式碼
$ftype = 'application/octet-stream';
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo !== FALSE) {
$fres = @finfo_file($finfo, $file);
if ( ($fres !== FALSE)
&& is_string($fres)
&& (strlen($fres)>0)) {
$ftype = $fres;
}
@finfo_close($finfo);
}
我花了好多天尋找一個包含媒體類型實際描述的資料庫,例如:
finfo(.png) --> "image/png" --> "PNG 圖片".
在基於 Ubuntu 的作業系統中,您可以在 /usr/share/mime 找到已翻譯的資料庫
http://manpages.ubuntu.com/manpages/hardy/en/man5/gnome-mime.5.html
相同功能的物件導向版本(稍微改進)
<?php
$file = '<somefile>';
$ftype = 'application/octet-stream';
$finfo = @new finfo(FILEINFO_MIME);
$fres = @$finfo->file($file);
if (is_string($fres) && !empty($fres)) {
$ftype = $fres;
}
?>
使用 `finfo_file()` 時,您可能會遇到需要注意的類似以下結果:`image/png; charset=binary`
我曾想使用 fileinfo 來檢查檔案是否為 gzip 或 bzip2。然而,壓縮檔案的 MIME 類型是「data」,因為壓縮是一種編碼而不是類型。
gzip 檔案以二進位 1f8b 開頭。
bzip2 檔案以魔術位元組 'B' 'Z' 'h' 開頭。
例如:
<?php
$s = file_get_contents("somefilepath");
if ( bin2hex(substr($s,0,2)) == '1f8b' ) {/* 有可能是 gzip 檔案 */}
if( substr($s,0,3) == 'BZh' ){/* 有可能是 bzip2 檔案 */}
?>
我不是編碼專家。我只用自己的幾個編碼檔案做了測試。
這裡有一個包裝器,可以正確識別 Microsoft Office 2007 文件。它使用、編輯和添加更多檔案副檔名/MIME 類型都很簡單直接。
<?php
function get_mimetype($filepath) {
if(!preg_match('/\.[^\/\\\\]+$/',$filepath)) {
return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
}
switch(strtolower(preg_replace('/^.*\./','',$filepath))) {
// START MS Office 2007 Docs
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
case 'docm':
return 'application/vnd.ms-word.document.macroEnabled.12';
case 'dotx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
case 'dotm':
return 'application/vnd.ms-word.template.macroEnabled.12';
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
case 'xlsm':
return 'application/vnd.ms-excel.sheet.macroEnabled.12';
case 'xltx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
case 'xltm':
return 'application/vnd.ms-excel.template.macroEnabled.12';
case 'xlsb':
return 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
case 'xlam':
return 'application/vnd.ms-excel.addin.macroEnabled.12';
case 'pptx':
return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
case 'pptm':
return 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
case 'ppsx':
return 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
case 'ppsm':
return 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
case 'potx':
return 'application/vnd.openxmlformats-officedocument.presentationml.template';
case 'potm':
return 'application/vnd.ms-powerpoint.template.macroEnabled.12';
case 'ppam':
return 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
case 'sldx':
return 'application/vnd.openxmlformats-officedocument.presentationml.slide';
case 'sldm':
return 'application/vnd.ms-powerpoint.slide.macroEnabled.12';
case 'one':
return 'application/msonenote';
case 'onetoc2':
return 'application/msonenote';
case 'onetmp':
return 'application/msonenote';
case 'onepkg':
return 'application/msonenote';
case 'thmx':
return 'application/vnd.ms-officetheme';
//END MS Office 2007 Docs
}
return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
}
?>