從 URL 取得檔案副檔名是常見需求,但直接用 explode('.', $url) 取最後一段極不靠譜。本文分析常見錯誤,提供正確且健壯的解法。
<?php
// 原始碼問題
function getUrlPostfix($url) {
$url_arr = explode('.', $url);
$postfix = $url_arr[count($url_arr) - 1];
$substr = substr($postfix, 0, 3); // 只取前 3 字元?極不合理
return $substr;
}
$url = "https://www.bitsCN.com/index.html?id=1";
echo getUrlPostfix($url); // 輸出 "htm",但邏輯有多處錯誤
?>
?id=1 會被誤判為副檔名一部分#section 同樣會干擾www.example.com 中的 com 會被誤判/api/users 會回傳 userssubstr($postfix, 0, 3) 會截斷 html 為 htm、jpeg 為 jpe<?php
function getUrlExtension(string $url): ?string {
// 1. 解析 URL,取得 path 部分
$parsed = parse_url($url);
if (!$parsed || !isset($parsed['path'])) {
return null;
}
$path = $parsed['path'];
// 2. 使用 pathinfo 取得副檔名(自動處理多種情況)
$extension = pathinfo($path, PATHINFO_EXTENSION);
// 3. 回傳小寫標準化,無副檔名回傳 null
return $extension ? strtolower($extension) : null;
}
// 測試案例
$tests = [
'https://example.com/file.html' => 'html',
'https://example.com/file.HTML' => 'html',
'https://example.com/path/file.tar.gz' => 'gz', // 只取最後一段
'https://example.com/file?query=1' => 'html', // 忽略查詢字串
'https://example.com/file#anchor' => 'html', // 忽略錨點
'https://example.com/api/users' => null, // 無副檔名
'https://example.com/.htaccess' => 'htaccess', // 隱藏檔
'https://example.com/file.' => '', // 空副檔名
];
foreach ($tests as $url => $expected) {
$result = getUrlExtension($url);
$status = $result === $expected ? '✅' : '❌';
echo "$status $url => " . var_export($result, true) . " (期望: " . var_export($expected, true) . ")\n";
}
?>
<?php
function getFullExtension(string $url): ?string {
$parsed = parse_url($url);
if (!$parsed || !isset($parsed['path'])) return null;
$path = $parsed['path'];
$filename = basename($path);
// 找第一個點之後的所有內容
$pos = strpos($filename, '.');
if ($pos === false) return null;
return strtolower(substr($filename, $pos + 1));
}
// 測試
echo getFullExtension('https://example.com/archive.tar.gz'); // tar.gz
echo getFullExtension('https://example.com/.htaccess'); // htaccess
?>
<?php
function getExtensionSpl(string $url): ?string {
$parsed = parse_url($url);
if (!$parsed || !isset($parsed['path'])) return null;
$info = new SplFileInfo($parsed['path']);
$ext = $info->getExtension();
return $ext ? strtolower($ext) : null;
}
?>
<?php
$allowedExtensions = [
'image' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'],
'document' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md'],
'archive' => ['zip', 'rar', '7z', 'tar', 'gz', 'bz2'],
'video' => ['mp4', 'avi', 'mov', 'mkv', 'webm'],
'audio' => ['mp3', 'wav', 'flac', 'ogg', 'aac'],
'code' => ['php', 'js', 'css', 'html', 'htm', 'json', 'xml', 'yaml', 'yml'],
];
function isAllowedExtension(string $url, array $categories = []): bool {
$ext = getUrlExtension($url);
if (!$ext) return false;
$allowed = [];
foreach ($categories as $cat) {
$allowed = array_merge($allowed, $allowedExtensions[$cat] ?? []);
}
return in_array($ext, $allowed, true);
}
// 使用
if (isAllowedExtension($uploadUrl, ['image', 'document'])) {
// 允許上傳
}
?>
parse_url() 先提取 path,避免查詢字串、錨點、用戶資訊干擾pathinfo() 或 SplFileInfo 取得副檔名,正確處理邊界情況null 或空字串,而非誤傳路徑片段.tar.gz 類雙重副檔名,pathinfo() 只取最後一段,需特殊處理