萬盛學電腦網

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

PHP 實現檔案下載的兩種標準方式與最佳實踐

方法一:標準 HTTP 下載頭(推薦)

適用於任意檔案類型,支援斷點續傳(需額外處理 Range 請求)。

<?php
function downloadFile(string $filePath, string $fileName = ''): void
{
    if (!is_file($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        exit('檔案不存在或不可讀');
    }

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

    // 清除輸出緩衝
    while (ob_get_level()) ob_end_clean();

    header('Content-Description: File Transfer');
    header('Content-Type: ' . $mime);
    header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $fileSize);
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Expires: 0');

    // 支援大檔案分塊輸出,避免記憶體耗盡
    $handle = fopen($filePath, 'rb');
    while (!feof($handle)) {
        echo fread($handle, 8192);
        flush();
    }
    fclose($handle);
    exit;
}
?>

方法二:簡易版(僅適用小檔案)

<?php
function simpleDownload(string $filePath): void
{
    $info = pathinfo($filePath);
    header('Content-Type: application/x-' . $info['extension']);
    header('Content-Disposition: attachment; filename="' . $info['basename'] . '"');
    header('Content-Length: ' . filesize($filePath));
    readfile($filePath); // 會將整個檔案讀入記憶體
    exit;
}
?>

關鍵細節與坑點

  • 檔名編碼:使用 `rawurlencode()` 並雙引號包裹,相容中文檔名。
  • 輸出緩衝:下載前必須清空所有 `ob_*` 緩衝,否則會導致檔案損壞或頭部輸出錯誤。
  • 大檔案:禁用 `readfile()`,改用 `fread` 分塊輸出 + `flush()`。
  • 斷點續傳:需處理 `HTTP_RANGE` 請求頭,返回 `206 Partial Content`,生產環境建議用 Nginx `X-Accel-Redirect` 或 Apache `mod_xsendfile` 卸載 PHP。
  • 權限控制:下載前驗證用戶權限,避免直接暴露檔案路徑。

生產環境建議

高併發、大檔案場景請使用 X-Sendfile / X-Accel-Redirect 讓 Web Server 直接發送檔案,PHP 僅負責權限驗證與頭部設置。

copyright © 萬盛學電腦網 all rights reserved