萬盛學電腦網

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

PHP 高效檔案下載:X-Sendfile 讓 Web Server 直接傳輸,釋放 PHP 進程

傳統 PHP 下載檔案需讀取檔案內容經由 PHP 輸出,佔用記憶體與進程。利用 Web Server 的 X-Sendfile(Apache)/ X-Accel-Redirect(Nginx)機制,可讓 Web Server 直接傳送檔案,PHP 僅負責權限檢查與標頭設定,大幅提升效能與並發能力。

傳統 readfile() 方式的缺點

<?php
$file = "/tmp/大檔案.tar.gz";
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header("Content-Length: ".filesize($file));
readfile($file); // PHP 進程阻塞讀取、輸出,佔用記憶體/CPU
?>
  • PHP 進程持續佔用直到傳輸完成。
  • 大檔案易觸發 memory_limit、max_execution_time。
  • Nginx+PHP-FPM 分離部署時,增加網路 IO 開銷。

中文檔名相容性處理

$filename = basename($file);
$ua = $_SERVER['HTTP_USER_AGENT'];
$encoded = rawurlencode($filename);
$encoded = str_replace('+', '%20', $encoded); // RFC 5987

if (preg_match('/MSIE|Trident|Edge/', $ua)) {
    header('Content-Disposition: attachment; filename="'.$encoded.'"');
} elseif (preg_match('/Firefox/', $ua)) {
    header("Content-Disposition: attachment; filename*=utf-8''{$filename}");
} else {
    header('Content-Disposition: attachment; filename="'.$filename.'"');
}

進階方案:X-Sendfile (Apache) / X-Accel-Redirect (Nginx)

Apache + mod_xsendfile

  1. 安裝模組:apt-get install libapache2-mod-xsendfile (Debian/Ubuntu)
  2. 啟用:a2enmod xsendfile
  3. 虛擬主機設定:XSendFile On、XSendFilePath /allowed/path/
  4. PHP 代碼:
    header("X-Sendfile: $file"); // Apache 直接接管傳輸
    // 不需要 readfile()、Content-Length 等

Nginx + X-Accel-Redirect

  1. Nginx 設定內部路徑映射:
    location /protected/ {
        internal;                    # 只允許內部重導向
        alias /real/path/to/files/;  # 實際檔案目錄
    }
  2. PHP 代碼:
    header("X-Accel-Redirect: /protected/" . basename($file));
    // Nginx 直接以高效非阻塞方式傳送檔案

Lighttpd

同樣支援 X-Sendfile 模組,設定方式類似 Apache。

效能對比

方式PHP 進程佔用記憶體並發能力適用場景
readfile()高(阻塞)中(緩衝區)低小檔案、簡單專案
X-Sendfile / X-Accel-Redirect極低(僅發標頭)極低極高大檔案、高並發、生產環境

結論: 生產環境提供檔案下載服務,強烈建議啟用 Web Server 級的 X-Sendfile/X-Accel-Redirect 機制。

copyright © 萬盛學電腦網 all rights reserved