核心方法對比
| 方法 | 程式碼 | 優點 | 缺點 | 推薦度 |
| pathinfo() | pathinfo($file, PATHINFO_EXTENSION) | 內建、處理路徑、支援無副檔名 | 較慢 (解析完整路徑) | ⭐⭐⭐⭐⭐ |
| SplFileInfo | (new SplFileInfo($file))->getExtension() | 物件導向、可鏈式、可取得其他資訊 | 建立物件開銷 | ⭐⭐⭐⭐ |
| strrchr + substr | substr(strrchr($file, '.'), 1) | 單純字串操作、快 | 無副檔名回傳空字串、點號在目錄名會誤判 | ⭐⭐⭐ |
| explode + end | end(explode('.', $file)) | 簡潔 | 同 strrchr,且 explode 建立陣列較慢 | ⭐⭐ |
| 正則 | preg_match('/\.([^.]+)$/', $file, $m) ? $m[1] : '' | 可處理複雜規則 | 過度殺傷、效能差 | ⭐ |
推薦:pathinfo() 標準用法
<?php
$files = [
'document.pdf',
'image.png',
'archive.tar.gz', // 雙副檔名
'script', // 無副檔名
'.htaccess', // 隱藏檔 (無主檔名)
'/path/to/file.txt', // 含路徑
'file.name.with.dots.txt', // 多點號
];
foreach ($files as $file) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
echo "{$file} => [{$ext}]\n";
}
/* 輸出:
document.pdf => [pdf]
image.png => [png]
archive.tar.gz => [gz] // 只取最後一段
script => [] // 空字串
.htaccess => [htaccess] // 視為副檔名
/path/to/file.txt => [txt] // 自動忽略路徑
file.name.with.dots.txt => [txt]
*/
進階:取得「完整副檔名」(如 .tar.gz)
<?php
function getFullExtension($filename)
{
$basename = basename($filename);
$pos = strpos($basename, '.');
if ($pos === false) return '';
// 找到第一個點號後的所有內容
return substr($basename, $pos + 1);
}
// 或使用正則
function getFullExtensionRegex($filename)
{
$basename = basename($filename);
if (preg_match('/^\.?([^.].*)$/', $basename, $m)) {
return $m[1];
}
return '';
}
$tests = ['archive.tar.gz', 'file.txt', '.htaccess', 'noext'];
foreach ($tests as $f) {
echo "$f => [" . getFullExtension($f) . "]\n";
}
/* 輸出:
archive.tar.gz => [tar.gz]
file.txt => [txt]
.htaccess => [htaccess]
noext => []
*/
安全應用:檔案上傳驗證副檔名
<?php
function isAllowedExtension($filename, array $allowedExts): bool
{
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// 正規化:移除前導點號 (pathinfo 不會回傳點號)
return in_array($ext, array_map('strtolower', $allowedExts), true);
}
// 允許的副檔名白名單
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx'];
// $_FILES['upload']['name'] 為用戶上傳原始檔名
if (isAllowedExtension($_FILES['upload']['name'], $allowed)) {
// 進一步驗證:MIME 類型、檔案內容 (finfo)
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['upload']['tmp_name']);
$allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
if (in_array($mime, $allowedMimes)) {
// 安全移動檔案
move_uploaded_file(...);
}
}
效能微調測試
<?php
$files = array_fill(0, 100000, '/very/long/path/to/file.name.with.many.dots.txt');
$start = microtime(true);
foreach ($files as $f) pathinfo($f, PATHINFO_EXTENSION);
echo "pathinfo: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
foreach ($files as $f) (new SplFileInfo($f))->getExtension();
echo "SplFileInfo: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
foreach ($files as $f) substr(strrchr($f, '.'), 1);
echo "strrchr: " . (microtime(true) - $start) . "s\n";
/* 典型輸出 (PHP 8.2):
pathinfo: 0.045s
SplFileInfo: 0.062s
strrchr: 0.018s (最快但最不安全)
*/
總結建議
- 通用專案:
pathinfo($file, PATHINFO_EXTENSION) — 標準、安全、可讀
- 高效能/大量檔案:
substr(strrchr($file, '.'), 1) 搭配 basename() 先取檔名 — 最快但需自行處理邊界
- 物件導向/需多檔案資訊:
SplFileInfo — 可同時取得 getFilename(), getBasename(), getPath(), getSize(), getMTime()
- 安全上傳:副檔名白名單 + MIME 類型驗證 (finfo) + 重新命名儲存
- 特殊需求:完整副檔名 (.tar.gz) 用自訂函式