萬盛學電腦網

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

PHP 檔案下載完整解決方案:支援斷點續傳、速度限制、大檔案記憶體優化

為什麼需要專業的檔案下載函數?

單純 readfile() 或 echo file_get_contents() 存在嚴重問題:大檔案佔滿記憶體、不支援斷點續傳(HTTP Range)、無法限速、無快取驗證(ETag/Last-Modified)、中文檔名跨瀏覽器亂碼。生產環境需要完整的 HTTP 協定支援。

企業級下載類核心功能

  • ✅ HTTP Range 斷點續傳(206 Partial Content)
  • ✅ 速度限制(Token Bucket 演算法)
  • ✅ ETag / Last-Modified / If-None-Match 快取驗證(304)
  • ✅ 記憶體恆定(分塊讀取 + flush)
  • ✅ RFC 5987 中文檔名編碼相容
  • ✅ X-Sendfile / Nginx X-Accel-Redirect 代理模式支援

核心實現:FileDownloader 類

<?php
class FileDownloader
{
    private string $filePath;
    private string $downloadName;
    private int $speedLimit = 0; // bytes/sec, 0 = unlimited
    private bool $forceDownload = true;
    private string $mimeType = 'application/octet-stream';
    private int $bufferSize = 8192; // 8KB chunks

    public function __construct(string $filePath, string $downloadName = '')
    {
        $this->filePath = $filePath;
        $this->downloadName = $downloadName ?: basename($filePath);
    }

    public function setSpeedLimit(int $bytesPerSecond): self
    {
        $this->speedLimit = max(0, $bytesPerSecond);
        return $this;
    }

    public function setMimeType(string $mime): self
    {
        $this->mimeType = $mime;
        return $this;
    }

    public function setBufferSize(int $bytes): self
    {
        $this->bufferSize = max(1024, $bytes);
        return $this;
    }

    public function useXSendfile(string $header = 'X-Accel-Redirect'): bool
    {
        if (!is_readable($this->filePath)) {
            http_response_code(404);
            return false;
        }

        // 交給 Nginx/Apache 處理傳輸,PHP 釋放進程
        header("$header: " . $this->sanitizePathForXSendfile($this->filePath));
        $this->sendCommonHeaders();
        return true;
    }

    public function send(): bool
    {
        if (!is_readable($this->filePath)) {
            http_response_code(404);
            return false;
        }

        $stat = stat($this->filePath);
        $fileSize = $stat['size'];
        $lastModified = $stat['mtime'];
        $etag = $this->generateEtag($stat);

        // 快取驗證
        if ($this->handleCacheValidation($lastModified, $etag)) {
            return true; // 304 已送出
        }

        // Range 處理
        [$start, $end, $isPartial] = $this->parseRangeHeader($fileSize);
        $contentLength = $end - $start + 1;

        // 發送標頭
        $this->sendDownloadHeaders($fileSize, $contentLength, $lastModified, $etag, $isPartial, $start, $end);

        // 串流輸出
        return $this->streamFile($start, $contentLength);
    }

    private function generateEtag(array $stat): string
    {
        $hash = md5($stat['mtime'] . '=' . $stat['ino'] . '=' . $stat['size']);
        return '"' . $hash . '-' . dechex(crc32($hash)) . '"';
    }

    private function handleCacheValidation(int $lastModified, string $etag): bool
    {
        // If-Modified-Since
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
            $ims = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
            if ($ims >= $lastModified) {
                http_response_code(304);
                header('ETag: ' . $etag);
                return true;
            }
        }

        // If-None-Match
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
            http_response_code(304);
            header('ETag: ' . $etag);
            return true;
        }

        // If-Unmodified-Since
        if (isset($_SERVER['HTTP_IF_UNMODIFIED_SINCE'])) {
            $ius = strtotime($_SERVER['HTTP_IF_UNMODIFIED_SINCE']);
            if ($ius < $lastModified) {
                http_response_code(412); // Precondition Failed
                return true;
            }
        }

        return false;
    }

    private function parseRangeHeader(int $fileSize): array
    {
        if (empty($_SERVER['HTTP_RANGE'])) {
            return [0, $fileSize - 1, false];
        }

        if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $m)) {
            return [0, $fileSize - 1, false];
        }

        $start = $m[1] !== '' ? (int)$m[1] : $fileSize - (int)$m[2];
        $end = $m[2] !== '' ? (int)$m[2] : $fileSize - 1;

        $start = max(0, min($start, $fileSize - 1));
        $end = max($start, min($end, $fileSize - 1));

        return [$start, $end, true];
    }

    private function sendDownloadHeaders(int $fileSize, int $contentLength, int $lastModified, string $etag, bool $isPartial, int $start, int $end): void
    {
        if ($isPartial) {
            http_response_code(206);
            header("Content-Range: bytes $start-$end/$fileSize");
        } else {
            http_response_code(200);
        }

        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
        header('ETag: ' . $etag);
        header('Accept-Ranges: bytes');
        header('Content-Type: ' . $this->mimeType);
        header('Content-Length: ' . $contentLength);

        if ($this->forceDownload) {
            $encodedName = rawurlencode($this->downloadName);
            // RFC 5987 + 向下相容
            header("Content-Disposition: attachment; filename*=UTF-8''{$encodedName}; filename=\"{$encodedName}\"");
        }

        header('Cache-Control: public, must-revalidate, max-age=0');
        header('Pragma: public');
        header('Content-Transfer-Encoding: binary');
    }

    private function streamFile(int $start, int $contentLength): bool
    {
        $fp = fopen($this->filePath, 'rb');
        if (!$fp) return false;

        fseek($fp, $start);
        $bytesSent = 0;
        $chunkTimeTarget = $this->speedLimit ? ($this->bufferSize * 1_000_000 / $this->speedLimit) : 0;

        while ($bytesSent < $contentLength && !feof($fp) && connection_status() === CONNECTION_NORMAL) {
            $chunkStart = hrtime(true);

            $readSize = min($this->bufferSize, $contentLength - $bytesSent);
            $buffer = fread($fp, $readSize);
            if ($buffer === false) break;

            echo $buffer;
            @ob_flush();
            @flush();

            $bytesSent += strlen($buffer);

            if ($this->speedLimit > 0) {
                $elapsedUs = (hrtime(true) - $chunkStart) / 1000;
                $sleepUs = $chunkTimeTarget - $elapsedUs;
                if ($sleepUs > 0) {
                    usleep((int)$sleepUs);
                }
            }
        }

        fclose($fp);
        return connection_status() === CONNECTION_NORMAL;
    }

    private function sanitizePathForXSendfile(string $path): string
    {
        // 根據 Web Server 設定調整:Nginx 需要 internal location 映射路徑
        return $path;
    }

    private function sendCommonHeaders(): void
    {
        $stat = stat($this->filePath);
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stat['mtime']) . ' GMT');
        header('ETag: ' . $this->generateEtag($stat));
        header('Content-Type: ' . $this->mimeType);
        header('Accept-Ranges: bytes');
        if ($this->forceDownload) {
            $encoded = rawurlencode($this->downloadName);
            header("Content-Disposition: attachment; filename*=UTF-8''{$encoded}; filename=\"{$encoded}\"");
        }
    }
}
?>

使用範例

<?php
require 'FileDownloader.php';

// 一般下載
$downloader = new FileDownloader('/data/exports/report_2024.xlsx', '2024年營收報表.xlsx')
    ->setSpeedLimit(1024 * 1024) // 限速 1MB/s
    ->setMimeType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$downloader->send();

// 或使用 X-Sendfile(需 Nginx/Apache 配合配置)
// $downloader->useXSendfile('X-Accel-Redirect');
?>

Nginx X-Accel-Redirect 配置範例

# nginx.conf
location /protected-files/ {
    internal;           # 只允許內部重導向
    alias /data/;       # 對應實體路徑
    add_header Content-Disposition "attachment";
}

PHP 端:header('X-Accel-Redirect: /protected-files/exports/report_2024.xlsx');

大檔案記憶體優化對比

方法1GB 檔案記憶體支援 Range支援限速適用場景
readfile()~1GB (OOM 風險)❌❌小檔案
file_get_contents + echo~1GB❌❌不推薦
fread + flush 循環~8KB (緩衝區)手動實現手動實現中等檔案
FileDownloader 類~8KB✅ 完整✅ Token Bucket生產環境
X-Sendfile~1KB (PHP 進程即釋放)✅ Web Server 處理✅ Web Server 模組超大檔/高併發

總結

專業的檔案下載不只是「輸出內容」,而是完整實作 HTTP 協定語意:Range 請求、條件請求、內容協商、流量控制。上述 FileDownloader 類別可直接投入生產,搭配 Nginx X-Accel-Redirect 更能將 IO 壓力從 PHP 進程卸載,實現高併發大檔案分發。

copyright © 萬盛學電腦網 all rights reserved