萬盛學電腦網

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

PHP 控制檔案下載速度:流量控制與頻寬限制實作

前言

提供檔案下載服務時,為避免單一使用者佔滿頻寬、影響其他服務,或實現「免費用戶限速、付費用戶全速」的商業模式,需要在 PHP 層面實作下載速度控制。本文介紹基於 sleep/usleep 的基本限速、Token Bucket 演算法平滑限速,以及交給 Web Server (Nginx/Apache) 處理的高效能方案。

基本限速實作(固定區塊 + 睡眠)

<?php
function downloadWithThrottle(string $filePath, float $kbPerSec = 100): void {
    if (!is_file($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        exit('檔案不存在');
    }

    $fileName = basename($filePath);
    $fileSize = filesize($filePath);
    $mimeType = mime_content_type($filePath) ?: 'application/octet-stream';

    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
    header('Content-Length: ' . $fileSize);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    header('Cache-Control: private, must-revalidate');
    header('Pragma: private');
    header('Expires: 0');

    $handle = fopen($filePath, 'rb');
    $chunkSize = 1024 * 8; // 8KB
    $bytesPerSecond = $kbPerSec * 1024;
    $microSecPerChunk = ($chunkSize / $bytesPerSecond) * 1_000_000;

    while (!feof($handle) && connection_status() === CONNECTION_NORMAL) {
        $chunk = fread($handle, $chunkSize);
        echo $chunk;
        @ob_flush();
        @flush();
        if ($microSecPerChunk > 0) {
            usleep((int)$microSecPerChunk);
        }
    }
    fclose($handle);
    exit;
}

進階:Token Bucket 平滑限速

固定睡眠會導致傳輸呈現鋸齒狀(傳→停→傳)。Token Bucket 允許突發傳輸,長期平均速率固定。

class TokenBucketThrottle {
    private float $rate;      // bytes/sec
    private float $burst;     // 最大突發 bytes
    private float $tokens;
    private float $lastRefill;

    public function __construct(float $kbPerSec, float $burstKb = null) {
        $this->rate = $kbPerSec * 1024;
        $this->burst = ($burstKb ?? $kbPerSec * 2) * 1024;
        $this->tokens = $this->burst;
        $this->lastRefill = microtime(true);
    }

    public function consume(int $bytes): void {
        $now = microtime(true);
        $elapsed = $now - $this->lastRefill;
        $this->tokens = min($this->burst, $this->tokens + $elapsed * $this->rate);
        $this->lastRefill = $now;

        if ($this->tokens < $bytes) {
            $wait = ($bytes - $this->tokens) / $this->rate;
            usleep((int)($wait * 1_000_000));
            $this->tokens = 0;
        } else {
            $this->tokens -= $bytes;
        }
    }
}

// 使用
$throttle = new TokenBucketThrottle(100, 200); // 100KB/s 平均,允許 200KB 突發
while ($chunk = fread($handle, 8192)) {
    $throttle->consume(strlen($chunk));
    echo $chunk;
    @ob_flush(); @flush();
}

高效能方案:Nginx limit_rate / X-Accel-Redirect

PHP 層面限速會佔用 PHP-FPM 進程、消耗 CPU(睡眠輪詢)。最佳做法是由 Nginx 直接傳檔並限速:

Nginx 設定

location /protected/ {
    internal;                    # 僅允許內部重導向
    alias /var/www/files/;       # 實體檔案路徑
    limit_rate 100k;             # 限速 100 KB/s
    limit_rate_after 1m;         # 前 1MB 不限速(加快啟動體驗)
}

# PHP 端
header('X-Accel-Redirect: /protected/' . $internalPath);
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
exit;

動態限速(依用戶等級)

location /protected/ {
    internal;
    alias /var/www/files/;
    # 從 PHP 傳入的 Header 讀取限速值
    limit_rate $http_x_limit_rate;
}

# PHP 端
$rate = $user->isVip() ? '0' : '100k'; // 0 = 不限速
header('X-Limit-Rate: ' . $rate);
header('X-Accel-Redirect: /protected/' . $path);

Apache mod_ratelimit 替代方案

<Location /downloads>
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 100   # KB/s
</Location>

安全性與穩健性補充

  • 連線中斷檢測:connection_status() === CONNECTION_NORMAL 及時停止讀取,釋放資源。
  • Range 請求支援:斷點續傳需解析 HTTP_RANGE,發送 206 Partial Content,Nginx X-Accel-Redirect 原生支援。
  • 大檔案 64-bit:32 位元 PHP filesize() 會溢位,需用 sprintf('%u', filesize($file)) 或升級 64 位元環境。
  • 權限驗證:下載前務必驗證用戶身份、檔案存取權、防盜鏈 Token。

總結

PHP 實作限速適合簡單場景或無法控制 Web Server 時;生產環境強烈建議使用 Nginx X-Accel-Redirect + limit_rate,效能最高、功能最全(突發緩衝、動態限速、零 PHP 進程佔用)。Token Bucket 演算法可作為 PHP 端輔助,或應用於 API 速率限制。

copyright © 萬盛學電腦網 all rights reserved