傳統 PHP 下載檔案需讀取檔案內容經由 PHP 輸出,佔用記憶體與進程。利用 Web Server 的 X-Sendfile(Apache)/ X-Accel-Redirect(Nginx)機制,可讓 Web Server 直接傳送檔案,PHP 僅負責權限檢查與標頭設定,大幅提升效能與並發能力。
<?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
?>
memory_limit、max_execution_time。$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.'"');
}
apt-get install libapache2-mod-xsendfile (Debian/Ubuntu)a2enmod xsendfileXSendFile On、XSendFilePath /allowed/path/header("X-Sendfile: $file"); // Apache 直接接管傳輸
// 不需要 readfile()、Content-Length 等
location /protected/ {
internal; # 只允許內部重導向
alias /real/path/to/files/; # 實際檔案目錄
}
header("X-Accel-Redirect: /protected/" . basename($file));
// Nginx 直接以高效非阻塞方式傳送檔案
同樣支援 X-Sendfile 模組,設定方式類似 Apache。
| 方式 | PHP 進程佔用 | 記憶體 | 並發能力 | 適用場景 |
|---|---|---|---|---|
| readfile() | 高(阻塞) | 中(緩衝區) | 低 | 小檔案、簡單專案 |
| X-Sendfile / X-Accel-Redirect | 極低(僅發標頭) | 極低 | 極高 | 大檔案、高並發、生產環境 |
結論: 生產環境提供檔案下載服務,強烈建議啟用 Web Server 級的 X-Sendfile/X-Accel-Redirect 機制。