萬盛學電腦網

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

PHP 檔案下載實現:Header + readfile 方案的優缺點與生產級替代方案

Header + readfile 的基本實現與隱患

最簡單的下載實現:

<?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
  • ❌ 無斷點續傳:不支援 HTTP Range,下載中斷需重頭開始
  • ❌ 無快取驗證:缺少 ETag/Last-Modified,浪費頻寬
  • ❌ 阻塞進程:傳輸期間 PHP-FPM worker 佔用,高併發迅速耗盡進程池
  • ❌ 中文檔名亂碼:缺少 RFC 5987 編碼,IE/Edge/舊版瀏覽器失效

進階版:分塊讀取 + flush(解決記憶體,但仍阻塞進程)

<?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 X-Accel-Redirect 完整配置(推薦生產方案)

# 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;
}
?>

Apache mod_xsendfile 配置

# httpd.conf 或 .htaccess
XSendFile on
XSendFilePath /var/www/files

# PHP
header('X-Sendfile: /var/www/files/secret/document.pdf');

雲原生方案:預簽名 URL(零 PHP 進程參與)

<?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]);
?>

安全檢查清單

  1. 路徑遍歷防護:realpath($filePath) 必須在允許目錄內
  2. 權限驗證:每次下載必須檢查用戶對該檔案的存取權
  3. 速率限制:防止單用戶佔滿頻寬(Nginx limit_rate 或應用層 Token Bucket)
  4. 審計日誌:記錄下載時間、用戶、檔案、IP、User-Agent
  5. 防熱連結:簽名 URL 時效短、一次性、綁定 User-Agent/IP

總結

header + readfile 只適合原型驗證。生產環境請根據架構選型:

  • 傳統 VM/實體機 + Nginx:X-Accel-Redirect(最佳平衡)
  • Apache 環境:mod_xsendfile
  • K8s/雲原生:預簽名 URL直連物件存儲
  • 必須在 PHP 處理邏輯:使用完整 FileDownloader 類(上篇)

核心原則:PHP 負責「授權與決策」,Web Server/Object Storage 負責「傳輸與流控」。

copyright © 萬盛學電腦網 all rights reserved