萬盛學電腦網

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

PHP 強制瀏覽器下載檔案而非預覽的 Header 設定完整指南

前言

預設情況下,瀏覽器會嘗試在頁面內預覽圖片、PDF、影音等檔案。若需強制觸發「另存新檔」對話框,必須發送正確的 HTTP Header。本文整理跨瀏覽器相容的最佳 Header 組合,並解決常見坑點。

核心 Header 組合

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

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

    // 必要 Header
    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"; filename*=UTF-8\'\'' . rawurlencode($fileName));
    header('Content-Length: ' . $fileSize);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');

    // 快取控制(視需求調整)
    header('Cache-Control: private, must-revalidate');
    header('Pragma: private');
    header('Expires: 0');

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

關鍵 Header 解析

Header作用注意事項
Content-Disposition指示瀏覽器下載而非顯示雙重 filename 編碼相容 RFC 5987 與舊版瀏覽器
Content-Length告知檔案大小,啟用進度條大檔案需確保 PHP 整數不溢位(64-bit 環境無憂)
Content-Transfer-Encoding: binary避免傳輸層編碼修改二進位資料對應 HTTP/1.1 標準
Accept-Ranges: bytes支援斷點續傳、多執行緒下載需搭配 Range 請求處理(見下文)
Cache-Control: private允許瀏覽器快取但禁止代理快取敏感檔案改用 no-store

大檔案與斷點續傳支援

readfile() 會將整個檔案讀入記憶體,大檔案易造成 OOM。正確做法:

function sendFileChunked(string $path, int $start = 0, int $end = null): void {
    $handle = fopen($path, 'rb');
    fseek($handle, $start);
    $buffer = 1024 * 8; // 8KB
    while (!feof($handle) && ($end === null || ftell($handle) <= $end)) {
        echo fread($handle, $buffer);
        @ob_flush(); @flush();
    }
    fclose($handle);
}

// 在 forceDownload 中加入 Range 處理
if (isset($_SERVER['HTTP_RANGE'])) {
    // 解析 Range header,發送 206 Partial Content
    // 實作略,參考 RFC 7233
}

常見問題排查

  • 檔名中文亂碼:必須使用 filename*=UTF-8''... 格式,舊版 IE 需額外 filename="..." 雙重寫入。
  • 輸出前有空白/BOM:確保 PHP 檔案無 BOM、?> 前無空白、關閉 output_buffering 或手動 ob_clean()。
  • Nginx + PHP-FPM 截斷輸出:調整 fastcgi_buffers、fastcgi_max_temp_file_size,或啟用 X-Accel-Redirect 讓 Nginx 直接傳檔。
  • SSL/HTTPS 下 IE 無法下載:避免 Cache-Control: no-store,改用 private。

最佳實踐:X-Sendfile / X-Accel-Redirect

高流量站點應將檔案傳輸卸載給 Web Server:

// PHP 僅驗證權限,發送內部導向 Header
header('X-Accel-Redirect: /protected-files/' . $internalPath);
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
exit;
// Nginx 設定:location /protected-files { internal; alias /var/www/files/; }

此方式零 PHP 記憶體佔用、支援 sendfile 系統呼叫、可處理 TB 級大檔。

總結

正確的 Header 組合是強制下載的基礎,但生產環境更應關注大檔案傳輸效能與安全性。採用 X-Accel-Redirect 架構分離權限驗證與檔案傳輸,是企業級應用的標準做法。

copyright © 萬盛學電腦網 all rights reserved