萬盛學電腦網

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

跨瀏覽器 PHP 下載中文檔名亂碼解決方案

前言

HTTP 標準 Content-Disposition 歷史上僅支援 ASCII,導致中文檔名在不同瀏覽器顯示不一。RFC 5987 定義了 filename* 參數支援 UTF-8,現代瀏覽器皆支援。本文提供相容所有主流瀏覽器的最佳實踐。

完整解決方案

<?php
function sendFileDownload($filePath, $fileName = '')
{
    if (!file_exists($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        die('檔案不存在');
    }

    $fileName = $fileName ?: basename($filePath);
    $fileSize = filesize($filePath);
    $mimeType = mime_content_type($filePath) ?: 'application/octet-stream';

    // 1. 基本 Header
    header('Content-Type: ' . $mimeType);
    header('Content-Length: ' . $fileSize);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    header('Cache-Control: private, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');

    // 2. 處理檔名編碼
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

    // RFC 5987 標準格式:filename*=UTF-8''encoded_filename
    $encodedName = rawurlencode($fileName);
    $encodedName = str_replace('+', '%20', $encodedName); // 修正空格編碼
    $disposition = "attachment; filename*=UTF-8''{$encodedName}";

    // 3. 針對舊版 IE/Edge (Legacy) 提供 fallback
    if (preg_match('/MSIE|Trident|Edge\/[0-9]{1,2}/', $ua)) {
        // 老 IE 不支援 filename*,使用 filename 參數,需依瀏覽器編碼
        // IE/Edge Legacy 期望 UTF-8 URL 編碼
        $disposition = "attachment; filename=\"{$encodedName}\"";
    }

    // 4. Safari 舊版相容(可選)
    // if (preg_match('/Safari\/[0-9]/', $ua) && !preg_match('/Chrome/', $ua)) { ... }

    header('Content-Disposition: ' . $disposition);

    // 5. 輸出檔案
    readfile($filePath);
    exit;
}

// 使用範例
$file = '/var/www/files/年度報表_2024.xlsx';
sendFileDownload($file, '年度報表_2024.xlsx');
?>

瀏覽器相容性測試結果

瀏覽器版本filename* (RFC 5987)filename (URL編碼)結果
Chrome60+✓✓正常
Firefox50+✓✓正常
Edge79+ (Chromium)✓✓正常
Edge Legacy<= 44✗✓ (UTF-8)正常
IE11✗✓ (UTF-8)正常
Safari13+✓✓正常
Safari< 13✗✓ (UTF-8)正常

進階:支援斷點續傳

function sendFileWithRange($filePath, $fileName = '')
{
    $fileSize = filesize($filePath);
    $rangeHeader = $_SERVER['HTTP_RANGE'] ?? '';

    header('Accept-Ranges: bytes');
    header('Content-Length: ' . $fileSize);

    if ($rangeHeader) {
        // 解析 Range: bytes=start-end
        preg_match('/bytes=(\d+)-(\d*)/', $rangeHeader, $matches);
        $start = (int)$matches[1];
        $end = isset($matches[2]) && $matches[2] ? (int)$matches[2] : $fileSize - 1;
        $end = min($end, $fileSize - 1);
        $length = $end - $start + 1;

        header('HTTP/1.1 206 Partial Content');
        header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
        header('Content-Length: ' . $length);

        $fp = fopen($filePath, 'rb');
        fseek($fp, $start);
        echo fread($fp, $length);
        fclose($fp);
    } else {
        // 完整傳輸
        sendFileDownload($filePath, $fileName);
    }
    exit;
}

總結

採用 filename*=UTF-8''encoded 作為標準,搭配 User-Agent 判斷為舊版 IE/Edge 提供 filename="urlencoded" fallback,即可完美解決跨瀏覽器中文檔名下載亂碼問題。

copyright © 萬盛學電腦網 all rights reserved