<?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
<?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() 真正發送到網路層 |
token bucket 演算法動態調整睡眠時間。max_execution_time、Nginx proxy_read_timeout、瀏覽器逾時。CLI 模式執行或調大逾時設定。rawurlencode() 編碼檔名,並確保 HTTP 標頭為 UTF-8。PHP 限速下載的核心是 分塊讀取 + flush() + usleep()。配合 Range 請求支援斷點續傳,前端使用 Fetch + ReadableStream 實現精確進度條。生產環境建議:
limit_rate 或 X-Accel-Redirect 處理(效能最佳、無 PHP 進程開銷)Swoole/RoadRunner 長駐進程 + 非阻塞 I/O