副檔名極易偽造,單靠 $_FILES['file']['type'] 或 pathinfo() 判斷圖片類型極不安全。正確做法是讀取檔案前幾位元組的 Magic Bytes (魔術位元組) 進行識別。本文詳細解析主流圖片格式的檔案頭特徵,並提供生產級的型別偵測函數。
| 格式 | 副檔名 | Magic Bytes (Hex) | ASCII 表示 | 位元組長度 |
|---|---|---|---|---|
| PNG | .png | 89 50 4E 47 0D 0A 1A 0A | ‰PNG\r\n\x1A\n | 8 |
| JPEG | .jpg, .jpeg | FF D8 FF | ÿØÿ | 3 (SOI 標記) |
| GIF87a | .gif | 47 49 46 38 37 61 | GIF87a | 6 |
| GIF89a | .gif | 47 49 46 38 39 61 | GIF89a | 6 |
| BMP | .bmp | 42 4D | BM | 2 |
| WebP | .webp | 52 49 46 46 (RIFF) + 57 45 42 50 (WEBP) | RIFF....WEBP | 12 |
| ICO | .ico | 00 00 01 00 | ... | 4 |
| TIFF (LE) | .tiff, .tif | 49 49 2A 00 | II*. | 4 |
| TIFF (BE) | .tiff, .tif | 4D 4D 00 2A | MM.* | 4 |
<?php
/**
* 根據檔案頭偵測圖片 MIME 類型
* @param string $filePath 檔案路徑
* @return string|null MIME 類型 (image/png, image/jpeg, image/gif, image/webp, image/bmp, image/x-icon, image/tiff) 或 null
*/
function detectImageMime(string $filePath): ?string {
if (!is_file($filePath) || !is_readable($filePath)) return null;
// 讀取前 16 位元組足以識別所有主流格式
$fp = fopen($filePath, 'rb');
if (!$fp) return null;
$header = fread($fp, 16);
fclose($fp);
if (strlen($header) < 12) return null; // 檔案太小
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (str_starts_with($header, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")) {
return 'image/png';
}
// JPEG: FF D8 FF (SOI + APP0/APP1/...)
if (str_starts_with($header, "\xFF\xD8\xFF")) {
return 'image/jpeg';
}
// GIF: GIF87a 或 GIF89a
if (str_starts_with($header, 'GIF87a') || str_starts_with($header, 'GIF89a')) {
return 'image/gif';
}
// WebP: RIFF....WEBP (位元組 0-3: RIFF, 8-11: WEBP)
if (str_starts_with($header, 'RIFF') && substr($header, 8, 4) === 'WEBP') {
return 'image/webp';
}
// BMP: BM
if (str_starts_with($header, 'BM')) {
return 'image/bmp';
}
// ICO: 00 00 01 00
if (str_starts_with($header, "\x00\x00\x01\x00")) {
return 'image/x-icon';
}
// TIFF: II*. 或 MM.*
if (str_starts_with($header, "\x49\x49\x2A\x00") || str_starts_with($header, "\x4D\x4D\x00\x2A")) {
return 'image/tiff';
}
return null;
}
/** 便利函數:取得副檔名建議 */
function getImageExtension(string $filePath): ?string {
$mime = detectImageMime($filePath);
return match($mime) {
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
'image/x-icon' => 'ico',
'image/tiff' => 'tiff',
default => null,
};
}
<?php
function detectImageMimeFromBinary(string $binary): ?string {
if (strlen($binary) < 12) return null;
// 相同邏輯,直接操作字串
if (str_starts_with($binary, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")) return 'image/png';
if (str_starts_with($binary, "\xFF\xD8\xFF")) return 'image/jpeg';
if (str_starts_with($binary, 'GIF87a') || str_starts_with($binary, 'GIF89a')) return 'image/gif';
if (str_starts_with($binary, 'RIFF') && substr($binary, 8, 4) === 'WEBP') return 'image/webp';
if (str_starts_with($binary, 'BM')) return 'image/bmp';
if (str_starts_with($binary, "\x00\x00\x01\x00")) return 'image/x-icon';
if (str_starts_with($binary, "\x49\x49\x2A\x00") || str_starts_with($binary, "\x4D\x4D\x00\x2A")) return 'image/tiff';
return null;
}
// 上傳處理範例
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
$file = $_FILES['image'];
// 1. 讀取前 16 位元組偵測 (不信任 $_FILES['type'])
$header = file_get_contents($file['tmp_name'], false, null, 0, 16);
$mime = detectImageMimeFromBinary($header);
$allowed = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
if (!$mime || !in_array($mime, $allowed)) {
die('不支援的圖片格式或檔案損壞');
}
// 2. 二次驗證:用 GD/ImageMagick 嘗試載入 (防多型攻擊)
$img = @imagecreatefromstring(file_get_contents($file['tmp_name']));
if (!$img) {
die('圖片資料損壞或包含惡意內容');
}
imagedestroy($img);
// 3. 產生安全檔名 (用偵測到的真實副檔名)
$ext = getImageExtension($file['tmp_name']) ?? 'bin';
$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$destPath = 'uploads/' . $safeName;
move_uploaded_file($file['tmp_name'], $destPath);
echo "上傳成功:$safeName (偵測類型: $mime)";
}
mime_content_type() 或 finfo?finfo_file() (Fileinfo 擴展) 其實內部就是讀取 Magic Bytes,功能更完整但需額外擴展與 magic 資料庫檔案。fileinfo 擴展,生產環境建議直接用 finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path),支援更多格式且維護由系統負責。駭客可構造同時符合 PNG 和 PHP 腳本的檔案 (Polyglot)。雙重防護:
$img = imagecreatefromstring($rawData);
imagepng($img, $safePath); // 或 imagejpeg/webp
imagedestroy($img);
location ~ \.php$ { deny all; })。<?php
$file = 'test.jpg'; // 5MB JPEG
$iterations = 1000;
$start = microtime(true);
for ($i=0; $i<$iterations; $i++) {
detectImageMime($file);
}
echo "檔案路徑版:", (microtime(true)-$start)*1000/$iterations, " ms/次\n";
$header = file_get_contents($file, false, null, 0, 16);
$start = microtime(true);
for ($i=0; $i<$iterations; $i++) {
detectImageMimeFromBinary($header);
}
echo "二進位字串版:", (microtime(true)-$start)*1000/$iterations, " ms/次\n";
// 典型結果:檔案版 ~0.02ms, 字串版 ~0.001ms (避免 I/O)
掌握 Magic Bytes 偵測,是建立安全檔案上傳系統的第一道關卡。結合 GD 重繪、路徑隨機化、執行權限隔離,構建多層防禦,才能有效抵禦檔案上傳攻擊向量。