<?php
$str = 'as.da.efg'; // 測試字符串:含多個點、無真實路徑
// 1. strrchr + substr
echo substr(strrchr($str, "."), 1) . "\n"; // efg
// 2. strrpos + substr
echo substr($str, strrpos($str, ".") + 1) . "\n"; // efg
// 3. explode + end
echo end(explode('.', $str)) . "\n"; // efg
// 4. pathinfo() 返回數組
$file = pathinfo($str);
echo $file['extension'] . "\n"; // efg
// 5. pathinfo() 指定常量(推薦)
echo pathinfo($str, PATHINFO_EXTENSION) . "\n"; // efg
?>
| 測試路徑 | 預期結果 | 方法 1-3 | 方法 4 | 方法 5 ✅ |
|---|---|---|---|---|
/home/test.d/test.txt | txt | ✅ txt | ✅ txt | ✅ txt |
/home/test.d/test | 無擴展名 | ❌ 返回 test | ⚠️ 警告 + 空 | ✅ 空字符串 |
test | 無擴展名 | ❌ 返回 test | ⚠️ 警告 + 空 | ✅ 空字符串 |
.htaccess | 隱藏文件無擴展名 | ❌ 返回 htaccess | ⚠️ 警告 | ✅ 空字符串 |
.htaccess 會誤判為擴展名Undefined array key 警告<?php
$path = '/www/htdocs/your_image.jpg';
print_r(pathinfo($path));
/* 輸出:
Array
(
[dirname] => /www/htdocs
[basename] => your_image.jpg
[extension] => jpg
[filename] => your_image // PHP 5.2+
)
*/
?>
| 常量 | 值 | 含義 | 返回類型 |
|---|---|---|---|
| PATHINFO_DIRNAME | 1 | 目錄路徑 | string |
| PATHINFO_BASENAME | 2 | 文件名(含擴展名) | string |
| PATHINFO_EXTENSION | 4 | 擴展名(無點) | string|空字符串 |
| PATHINFO_FILENAME | 8 | 文件名(不含擴展名) | string |
注意: 常量值為位掩碼,但 不支持位運算組合,pathinfo($file, PATHINFO_EXTENSION | PATHINFO_FILENAME) 只會返回值最小的常量(即 DIRNAME)。
<?php
/**
* 安全獲取文件擴展名(小寫、無點)
* @param string $path 文件路徑或文件名
* @return string 擴展名,無則返回空字符串
*/
function getExtension(string $path): string {
// pathinfo 內部已處理路徑分隔符、隱藏文件、多點等邊界情況
$ext = pathinfo($path, PATHINFO_EXTENSION);
return strtolower($ext);
}
// 測試
var_dump(getExtension('/home/test.d/test.txt')); // "txt"
var_dump(getExtension('/home/test.d/test')); // ""
var_dump(getExtension('.htaccess')); // ""
var_dump(getExtension('archive.tar.gz')); // "gz" (只取最後一段)
?>
<?php
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file('/path/to/file.png'); // image/png
// 比單純擴展名更可靠,防偽裝上傳
?>
結論:永遠使用 pathinfo($path, PATHINFO_EXTENSION),標準庫已幫你處理好所有邊界情況,別再造輪子了。