提供檔案下載服務時,為避免單一使用者佔滿頻寬、影響其他服務,或實現「免費用戶限速、付費用戶全速」的商業模式,需要在 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 允許突發傳輸,長期平均速率固定。
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();
}
PHP 層面限速會佔用 PHP-FPM 進程、消耗 CPU(睡眠輪詢)。最佳做法是由 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);
<Location /downloads>
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 100 # KB/s
</Location>
connection_status() === CONNECTION_NORMAL 及時停止讀取,釋放資源。HTTP_RANGE,發送 206 Partial Content,Nginx X-Accel-Redirect 原生支援。filesize() 會溢位,需用 sprintf('%u', filesize($file)) 或升級 64 位元環境。PHP 實作限速適合簡單場景或無法控制 Web Server 時;生產環境強烈建議使用 Nginx X-Accel-Redirect + limit_rate,效能最高、功能最全(突發緩衝、動態限速、零 PHP 進程佔用)。Token Bucket 演算法可作為 PHP 端輔助,或應用於 API 速率限制。