萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 從 URL 取得副檔名的正確方法與常見陷阱

前言

從 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",但邏輯有多處錯誤
?>

主要問題

  1. 查詢字串干擾:?id=1 會被誤判為副檔名一部分
  2. 錨點干擾:#section 同樣會干擾
  3. 多層子域名:www.example.com 中的 com 會被誤判
  4. 無副檔名情況:/api/users 會回傳 users
  5. 任意截取 3 字元:substr($postfix, 0, 3) 會截斷 html 為 htm、jpeg 為 jpe

✅ 正確解法:使用 parse_url() + pathinfo()

<?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";
}
?>

進階需求:取得完整副檔名(如 .tar.gz)

<?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
?>

替代方案:SplFileInfo(物件導向)

<?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() 只取最後一段,需特殊處理
copyright © 萬盛學電腦網 all rights reserved