取得檔案副檔名看似簡單,但面對「多重點」、「無副檔名」、「大小寫不一」、「URL 含查詢字串」等情況,單純用 explode('.', $file) 容易出錯。本文整理 5 種方法,分析優缺點,給出生產環境建議。
| 方法 | 程式碼 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| pathinfo() | pathinfo($file, PATHINFO_EXTENSION) | 內建、處理路徑分隔符、可同時取得檔名/目錄 | 無副檔名回傳空字串 | ✅ 推薦首選 |
| SplFileInfo | (new SplFileInfo($file))->getExtension() | 物件導向、可鏈式呼叫、支援更多檔案資訊 | 物件建立開銷稍大 | 需同時取得多項檔案資訊時 |
| strrchr() | strrchr($file, '.') 後 substr(1) | 極快、無函數呼叫開銷 | 目錄名含點會誤判、無副檔名回傳 false | 極高效能需求、確定輸入為純檔名 |
| explode + end | end(explode('.', $file)) | 直觀易懂 | 修改陣列指標、多重點錯誤、效能差 | 不推薦 |
| 正則表達式 | preg_match('/\.([^.]+)$/', $file, $m) | 可同時驗證格式 | 過度殺傷、效能最差 | 需複雜驗證邏輯時 |
<?php
/**
* 取得檔案副檔名(小寫、無點號)
*
* @param string $path 檔案路徑或 URL
* @param bool $stripQuery 是否移除查詢字串
* @return string|null 副檔名,無則回傳 null
*/
function getFileExtension(string $path, bool $stripQuery = true): ?string {
// 移除 URL 查詢字串與片段
if ($stripQuery) {
$path = parse_url($path, PHP_URL_PATH) ?? $path;
}
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext === '') return null;
return strtolower($ext);
}
// 測試案例
$tests = [
'image.jpg' => 'jpg',
'archive.tar.gz' => 'gz',
'/var/www/file' => null,
'document.PDF' => 'pdf',
'https://cdn.example.com/avatar.png?token=abc' => 'png',
'file.name.with.dots.txt' => 'txt',
'.htaccess' => 'htaccess', // 隱藏檔視為無副檔名或全名視為副檔名,視業務定義
];
foreach ($tests as $input => $expected) {
$result = getFileExtension($input);
echo "[$input] => " . ($result ?? 'null') . " " . ($result === $expected ? '✅' : "❌ (期望: $expected)") . "\n";
}
副檔名不可信(可任意改名),安全敏感場景必須檢查檔案內容(Magic Bytes):
function getMimeFromContent(string $filePath): ?string {
$finfo = new finfo(FILEINFO_MIME_TYPE);
return $finfo->file($filePath);
}
$allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
$ext = getFileExtension($uploadedFile);
$mime = getMimeFromContent($uploadedFile);
if ($ext && $mime && in_array($mime, $allowedMimes, true)) {
// 通過雙重驗證
}
.env、.gitignore,pathinfo 會回傳完整檔名作為 extension,需業務邏輯判斷。file%20name.jpg 需先 urldecode 再處理。shell.php.jpg,僅取最後一段(jpg),但安全掃描需檢查完整名稱。首選 pathinfo($file, PATHINFO_EXTENSION),配合 strtolower 與 URL 查詢字串移除。物件導向場景用 SplFileInfo。安全敏感操作務必結合 finfo 檢查實際 MIME 類型,不可僅信任副檔名。