最簡單的下載實現:
<?php
$file = '/path/to/secret/document.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="document.pdf"');
header('Content-Length: ' . filesize($file));
readfile($file);
?>
這段代碼在小檔案、低併發下能工作,但生產環境存在嚴重缺陷:
readfile() 內部仍會將檔案讀入 PHP 記憶體再輸出,大檔案直接 OOM<?php
function downloadWithChunkedRead(string $filePath, string $filename = '', int $chunkSize = 8192): void
{
if (!is_readable($filePath)) {
http_response_code(404);
exit('File not found');
}
$fileSize = filesize($filePath);
$filename = $filename ?: basename($filePath);
$encoded = rawurlencode($filename);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . $encoded . '; filename="' . $encoded . '"');
header('Content-Length: ' . $fileSize);
header('Accept-Ranges: bytes');
header('Cache-Control: public, must-revalidate');
header('Pragma: public');
$fp = fopen($filePath, 'rb');
while (!feof($fp) && connection_status() === CONNECTION_NORMAL) {
echo fread($fp, $chunkSize);
@ob_flush();
@flush();
}
fclose($fp);
}
?>
改進:記憶體恆定(~chunkSize),但仍阻塞 PHP worker,且未處理 Range 請求。
| 方案 | 記憶體 | 斷點續傳 | PHP 進程佔用 | 配置複雜度 | 推薦場景 |
|---|---|---|---|---|---|
| readfile() | 高 | ❌ | 高 | 低 | 測試/小檔 |
| fread+flush 循環 | 低 | 手動 | 高 | 中 | 中檔/無高併發 |
| 完整 Range 實現(上篇) | 低 | ✅ | 高 | 高 | 需精確控制 |
| X-Sendfile (Apache) | 極低 | ✅ | 極低 | 中 | Apache 環境 |
| X-Accel-Redirect (Nginx) | 極低 | ✅ | 極低 | 中 | 生產首選 |
| 雲存儲簽名 URL | 零 | ✅ | 零 | 低 | 雲原生/極大檔 |
# nginx.conf
server {
# 內部位置,僅允許內部重導向
location /internal-files/ {
internal;
alias /var/www/files/; # 實體儲存路徑
# 可選:限速
# limit_rate 1m;
# 可選:強制下載
# add_header Content-Disposition "attachment";
}
# 業務入口
location /download/ {
# PHP 處理權限驗證、日誌記錄、簽名驗證
fastcgi_pass php-fpm;
include fastcgi_params;
}
}
<?php
// PHP 業務邏輯:驗證權限後發送 X-Accel-Redirect
function secureDownload(int $fileId, string $userToken): void
{
// 1. 驗證用戶權限、檔案存在、下載次數限制等
$fileRecord = verifyAndGetFileRecord($fileId, $userToken);
if (!$fileRecord) {
http_response_code(403);
exit('Forbidden');
}
// 2. 記錄下載日誌、扣減次數等業務邏輯
logDownload($fileId, $userToken);
// 3. 發送內部重導向頭部,Nginx 接管傳輸
$internalPath = '/internal-files/' . ltrim($fileRecord['storage_path'], '/');
header('X-Accel-Redirect: ' . $internalPath);
// 4. 可選:覆蓋檔名(需 Nginx 支援 header 透傳或 map 配置)
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($fileRecord['original_name']));
// 5. PHP 進程立即結束,不佔用 worker
exit;
}
?>
# httpd.conf 或 .htaccess
XSendFile on
XSendFilePath /var/www/files
# PHP
header('X-Sendfile: /var/www/files/secret/document.pdf');
<?php
// AWS S3 範例
use Aws\S3\S3Client;
$s3 = new S3Client([
'region' => 'ap-northeast-1',
'version' => 'latest',
]);
$cmd = $s3->getCommand('GetObject', [
'Bucket' => 'my-app-files',
'Key' => 'exports/report_2024.xlsx',
'ResponseContentDisposition' => 'attachment; filename*=UTF-8\'\'' . rawurlencode('2024年營收報表.xlsx'),
]);
$request = $s3->createPresignedRequest($cmd, '+15 minutes'); // 15 分鐘有效
$presignedUrl = (string)$request->getUri();
// 重導向或返回 JSON 給前端
header('Location: ' . $presignedUrl);
// 或 API 回應:json_encode(['download_url' => $presignedUrl]);
?>
realpath($filePath) 必須在允許目錄內limit_rate 或應用層 Token Bucket)header + readfile 只適合原型驗證。生產環境請根據架構選型:
FileDownloader 類(上篇)核心原則:PHP 負責「授權與決策」,Web Server/Object Storage 負責「傳輸與流控」。