萬盛學電腦網

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

PHP 限制檔案下載速度實作:節省頻寬、實現進度條、避免網路阻塞

為什麼要限制下載速度?

  • 頻寬公平: 防止單一大檔下載佔滿伺服器頻寬,影響其他使用者
  • 進度條實作: 受控的串流輸出才能精確計算並顯示下載進度
  • 防止阻塞: 避免一次性輸出大檔導致 PHP 記憶體飆升、Nginx/Apache 緩衝區溢位、TCP 視窗滿載
  • 付費/分級下載: 免費用戶限速,付費用戶全速
  • 流量成本控制: 云端出站流量計費時,平滑輸出降低峰值成本

核心原理:分塊輸出 + 微睡眠

<?php
/**
 * 限速下載檔案
 *
 * @param string $filePath     檔案絕對路徑
 * @param int    $speedLimitKB 每秒限制 KB(如 200 = 200KB/s)
 * @param string $filename     下載時顯示的檔名
 */
function downloadThrottled(string $filePath, int $speedLimitKB = 200, string $filename = ''): void
{
    if (!is_file($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        exit('File not found');
    }

    $filename = $filename ?: basename($filePath);
    $fileSize = filesize($filePath);
    $chunkSize = 8192; // 8KB 每塊
    $bytesPerSecond = $speedLimitKB * 1024;
    $microsecondsPerChunk = (int)(($chunkSize / $bytesPerSecond) * 1_000_000);

    // 標頭
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
    header('Content-Length: ' . $fileSize);
    header('Accept-Ranges: bytes');
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: public');
    // 關閉輸出緩衝,確保即時輸出
    while (ob_get_level()) ob_end_flush();

    $handle = fopen($filePath, 'rb');
    if (!$handle) {
        http_response_code(500);
        exit('Cannot open file');
    }

    try {
        $totalSent = 0;
        while (!feof($handle) && connection_status() === CONNECTION_NORMAL) {
            $chunk = fread($handle, $chunkSize);
            if ($chunk === false) break;

            echo $chunk;
            $totalSent += strlen($chunk);

            // 刷新輸出緩衝到客戶端
            flush();

            // 限速:計算理論耗時 vs 實際耗時,微睡眠補差
            if ($speedLimitKB > 0) {
                usleep($microsecondsPerChunk);
            }
        }
    } finally {
        fclose($handle);
    }

    // 記錄下載日誌
    error_log(sprintf(
        'DOWNLOAD: file=%s size=%d sent=%d speed=%dKB/s ip=%s ua=%s',
        $filePath, $fileSize, $totalSent, $speedLimitKB,
        $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
    ));
}

// 使用範例
// downloadThrottled('/data/files/video.mp4', 500, 'lesson_01.mp4'); // 限速 500KB/s

進階版:支援斷點續傳(Range Request)

<?php
function downloadWithRange(string $filePath, int $speedLimitKB = 0): void
{
    if (!is_file($filePath)) { http_response_code(404); exit; }

    $fileSize = filesize($filePath);
    $fileName = basename($filePath);
    $handle = fopen($filePath, 'rb');

    // 處理 Range 標頭
    $start = 0;
    $end = $fileSize - 1;
    $statusCode = 200;

    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        if (preg_match('/bytes=(\d+)-(\d*)/', $range, $matches)) {
            $start = (int)$matches[1];
            $end = $matches[2] !== '' ? (int)$matches[2] : $fileSize - 1;
            if ($start >= $fileSize || $end >= $fileSize || $start > $end) {
                header('HTTP/1.1 416 Range Not Satisfiable');
                header('Content-Range: bytes */' . $fileSize);
                exit;
            }
            $statusCode = 206; // Partial Content
        }
    }

    $contentLength = $end - $start + 1;

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
    header('Content-Length: ' . $contentLength);
    header('Accept-Ranges: bytes');
    header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
    http_response_code($statusCode);

    if ($statusCode === 206) {
        header('Cache-Control: no-cache, must-revalidate');
    }

    // 定位到起始位置
    fseek($handle, $start);

    $remaining = $contentLength;
    $chunkSize = 8192;
    $bytesPerSecond = $speedLimitKB * 1024;
    $usPerChunk = $speedLimitKB > 0 ? (int)(($chunkSize / $bytesPerSecond) * 1_000_000) : 0;

    while (ob_get_level()) ob_end_flush();

    try {
        while ($remaining > 0 && connection_status() === CONNECTION_NORMAL) {
            $readSize = min($chunkSize, $remaining);
            $chunk = fread($handle, $readSize);
            if ($chunk === false || $chunk === '') break;

            echo $chunk;
            $remaining -= strlen($chunk);
            flush();

            if ($usPerChunk > 0) usleep($usPerChunk);
        }
    } finally {
        fclose($handle);
    }
}

前端進度條實作(配合限速下載)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>下載進度示範</title>
    <style>
        .progress-bar { width: 100%; height: 24px; background: #eee; border-radius: 4px; overflow: hidden; }
        .progress-fill { height: 100%; background: linear-gradient(90deg, #3498db, #2980b9); transition: width 0.3s; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.85rem; }
    </style>
</head>
<body>
    <div style="max-width: 600px; margin: 2rem auto; padding: 1rem;">
        <h3>檔案下載進度</h3>
        <div class="progress-bar"><div class="progress-fill" id="progress" style="width: 0%">0%</div></div>
        <p id="stats" style="margin-top: 0.5rem; font-size: 0.9rem; color: #666;">準備中...</p>
        <button id="startBtn" onclick="startDownload()">開始下載</button>
    </div>

    <script>
    async function startDownload() {
        const btn = document.getElementById('startBtn');
        const progress = document.getElementById('progress');
        const stats = document.getElementById('stats');
        btn.disabled = true;

        try {
            // 使用 Fetch + ReadableStream 監聽下載進度
            const response = await fetch('download.php?file=large.zip', {
                // credentials: 'include' // 若需 Cookie
            });

            if (!response.ok) throw new Error(`HTTP ${response.status}`);

            const total = parseInt(response.headers.get('Content-Length') || '0', 10);
            const reader = response.body.getReader();
            let received = 0;
            const chunks = [];

            while (true) {
                const {done, value} = await reader.read();
                if (done) break;
                chunks.push(value);
                received += value.length;

                if (total > 0) {
                    const pct = Math.round(received / total * 100);
                    progress.style.width = pct + '%';
                    progress.textContent = pct + '%';
                    stats.textContent = `${(received/1024/1024).toFixed(2)} MB / ${(total/1024/1024).toFixed(2)} MB (${pct}%)`;
                }
            }

            // 儲存檔案(需 File System Access API 或傳統 Blob 下載)
            const blob = new Blob(chunks);
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'large.zip';
            a.click();
            URL.revokeObjectURL(url);

            stats.textContent = '下載完成!';
        } catch (e) {
            stats.textContent = '錯誤: ' + e.message;
            console.error(e);
        } finally {
            btn.disabled = false;
        }
    }
    </script>
</body>
</html>

關鍵技術細節總結

技術點關鍵代碼說明
分塊讀取fread($handle, 8192)避免大檔一次性載入記憶體
即時輸出echo $chunk; flush();繞過 PHP/NGINX 緩衝,直接送達客戶端
限速計算usleep(($chunkSize/$bytesPerSec)*1e6)微睡眠控制平均頻寬
連線狀態檢查connection_status() === CONNECTION_NORMAL客戶端斷開時停止傳輸,釋放資源
斷點續傳HTTP_RANGE / 206 Partial Content支援下載工具續傳、多執行緒下載
關閉輸出緩衝while(ob_get_level()) ob_end_flush();確保 flush() 真正發送到網路層

常見問題與對策

  1. 實際速度超過限制: 系統排程、CPU 調度精度不足。改用 token bucket 演算法動態調整睡眠時間。
  2. 大檔案下載中斷: PHP max_execution_time、Nginx proxy_read_timeout、瀏覽器逾時。CLI 模式執行或調大逾時設定。
  3. 記憶體仍然飆高: 確認已關閉所有輸出緩衝,未在迴圈中累積字串變數。
  4. 中文檔名亂碼: 使用 rawurlencode() 編碼檔名,並確保 HTTP 標頭為 UTF-8。

總結

PHP 限速下載的核心是 分塊讀取 + flush() + usleep()。配合 Range 請求支援斷點續傳,前端使用 Fetch + ReadableStream 實現精確進度條。生產環境建議:

  • 靜態檔案交給 Nginx limit_rate 或 X-Accel-Redirect 處理(效能最佳、無 PHP 進程開銷)
  • 需權限驗證、動態檔案、統計分析時,才使用 PHP 限速輸出
  • 高併發場景改用 Swoole/RoadRunner 長駐進程 + 非阻塞 I/O
copyright © 萬盛學電腦網 all rights reserved