在 Web 開發中,上傳圖片後需獲取寬高、類型、MIME 以驗證合法性、生成縮略圖、設置響應式圖片屬性。getimagesize() 是 PHP 核心函數,**無需 GD/Imagick 擴展**,直接解析文件頭,極輕量且跨平台。本文系統講解返回值結構、常見陷阱、安全驗證模式與進階用法。
getimagesize(string $filename, array &$imageinfo = null): array|false
成功返回 7 元素數組 (索引 0-6),失敗返回 false 並觸發 E_WARNING。
| 索引/鍵 | 含義 | 示例 |
|---|---|---|
| 0 | 寬度 (像素) | 800 |
| 1 | 高度 (像素) | 600 |
| 2 | 圖片類型常量 | IMAGETYPE_JPEG (2), IMAGETYPE_PNG (3), IMAGETYPE_GIF (1), IMAGETYPE_WEBP (18) |
| 3 | HTML 屬性字符串 | 'width="800" height="600"' |
| 'bits' | 顏色深度 (bits per pixel) | 24 (真彩色), 8 (索引色) |
| 'channels' | 通道數 | 3 (RGB), 4 (RGBA/CMYK) |
| 'mime' | MIME 類型 | 'image/jpeg', 'image/png' |
第二參數 &$imageinfo 僅對 JPEG 有效,返回 APP 段數據(含 EXIF、IPTC),可用 iptcparse() 解析。
$file = 'uploads/photo.jpg';
$info = @getimagesize($file);
if ($info === false) {
die('非法圖片文件或文件不存在');
}
// 1. 直接輸出 img 標籤 (利用索引 3)
echo '
';
// 2. 解構賦值 (PHP 7.1+)
['0' => $w, '1' => $h, '2' => $type, '3' => $attr, 'mime' => $mime] = $info;
echo "{$w}x{$h} {$mime}";
// 3. 類型常量判斷
$allowed = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP];
if (!in_array($type, $allowed, true)) {
die('不支持的圖片格式');
}
function validate_image_upload(array $file): array {
// 1. 上傳錯誤碼檢查
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('上傳失敗,錯誤碼: ' . $file['error']);
}
// 2. 文件大小限制 (2MB)
if ($file['size'] > 2 * 1024 * 1024) {
throw new Exception('文件過大,限制 2MB');
}
// 3. MIME 類型雙重驗證 (getimagesize + finfo)
$info = @getimagesize($file['tmp_name']);
if ($info === false) {
throw new Exception('無法解析圖片,可能損壞或非圖片');
}
$allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($info['mime'], $allowedMimes, true)) {
throw new Exception('禁止的圖片類型: ' . $info['mime']);
}
// 4. 可選:finfo 二次驗證 (防偽裝文件頭)
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (!in_array($finfo->file($file['tmp_name']), $allowedMimes, true)) {
throw new Exception('MIME 偽裝檢測失敗');
}
// 5. 尺寸限制 (如最大 4000x4000)
if ($info[0] > 4000 || $info[1] > 4000) {
throw new Exception('圖片尺寸超限');
}
return $info; // 含 width, height, mime, type 常量
}
allow_url_fopen 可直接傳 URL,但**強烈不建議**生產環境使用(SSRF 風險、超時不可控、無法限制大小)。請先下載到臨時文件再驗證。getimagesize() 不支持 SVG (XML 文本),需自行解析 <svg width="..." height="..."> 或用 finfo 判斷 image/svg+xml。IMAGETYPE_ICO (21)。clearstatcache()。@getimagesize() 避免 Warning 污染日誌,配合嚴格的 === false 判斷。function make_thumbnail(string $src, string $dst, int $maxW = 300, int $maxH = 300): bool {
$info = @getimagesize($src);
if ($info === false) return false;
$srcW = $info[0]; $srcH = $info[1]; $type = $info[2];
// 計算目標尺寸 (等比縮放)
$ratio = min($maxW / $srcW, $maxH / $srcH);
if ($ratio >= 1) return copy($src, $dst); // 無需縮放
$dstW = (int)($srcW * $ratio);
$dstH = (int)($srcH * $ratio);
// 創建源圖資源
$create = [
IMAGETYPE_GIF => 'imagecreatefromgif',
IMAGETYPE_JPEG => 'imagecreatefromjpeg',
IMAGETYPE_PNG => 'imagecreatefrompng',
IMAGETYPE_WEBP => 'imagecreatefromwebp',
];
if (!isset($create[$type])) return false;
$srcIm = $create[$type]($src);
// 創建目標真彩色畫布
$dstIm = imagecreatetruecolor($dstW, $dstH);
// 保持透明通道 (GIF/PNG/WEBP)
if (in_array($type, [IMAGETYPE_GIF, IMAGETYPE_PNG, IMAGETYPE_WEBP], true)) {
imagecolortransparent($dstIm, imagecolorallocatealpha($dstIm, 0, 0, 0, 127));
imagealphablending($dstIm, false);
imagesavealpha($dstIm, true);
}
// 重採樣縮放
imagecopyresampled($dstIm, $srcIm, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
// 輸出
$output = [
IMAGETYPE_GIF => 'imagegif',
IMAGETYPE_JPEG => 'imagejpeg',
IMAGETYPE_PNG => 'imagepng',
IMAGETYPE_WEBP => 'imagewebp',
];
$quality = $type === IMAGETYPE_JPEG ? 85 : ($type === IMAGETYPE_WEBP ? 80 : null);
$ok = $quality ? $output[$type]($dstIm, $dst, $quality) : $output[$type]($dstIm, $dst);
imagedestroy($srcIm);
imagedestroy($dstIm);
return $ok;
}
getimagesize() 內部僅讀取文件前幾百字節,**極快**,可放心用於批量掃描。Imagick::pingImage() 僅讀取元數據,不解碼像素。getimagesize() 是 PHP 圖片處理的「瑞士軍刀」:零依賴、返回豐富元數據、支持主流格式。掌握其返回值結構、類型常量、MIME 雙重驗證、縮略圖生成流程,能構建安全高效的圖片上傳管線。記住:**永遠不要信任客戶端傳來的 Content-Type,伺服端必須二次驗證**。