簡易使用方式
<?php
$downloader = new HttpDownload();
$downloader->setByFile('/path/to/file.zip'); // 伺服器檔案路徑
$downloader->filename = 'download.zip'; // 另存為檔名
$downloader->download();
?>
核心類別結構
<?php
class HttpDownload {
public $data, $dataLen, $dataMod, $dataType;
public $useResume = true; // 支援斷點續傳
public $useAutoExit = false;
public $filename, $mime;
public $bufSize = 2048;
public $seekStart = 0, $seekEnd = -1;
public $bandwidth = 0, $speed = 0; // 限速控制
// 初始化:解析 HTTP_RANGE 標頭
public function initialize() { ... }
// 發送下載標頭
public function header($size, $start = null, $end = null) { ... }
// 主下載流程
public function download() {
if (!$this->initialize()) return false;
// 處理檔案/字串/重導向三種資料源
// 支援 Range 斷點續傳
// 支援限速($speed KB/s)
// 記錄錯誤日誌
}
// 設定資料來源
public function setByFile($path) { ... } // 本地檔案
public function setByData($string) { ... } // 字串資料
public function setByUrl($url) { ... } // 重導向
}
?>
關鍵功能解析
斷點續傳 (HTTP Range)
- 解析
$_SERVER['HTTP_RANGE'] (格式:bytes=start-end)
- 回應
206 Partial Content + Content-Range + Accept-Ranges: bytes
fseek() 定位檔案指標
限速控制
$speed 設定 KB/s 上限
- 迴圈中累計
$bandwidth,超過時 sleep(1)
多種資料源
- 本地檔案 (
data_type = 0):fopen('rb') + fread()
- 記憶體字串 (
data_type = 1):substr() 切片輸出
- 外部重導向 (
data_type = 2):header('Location: ...')
生產環境建議
- 加入
ETag / Last-Modified 快取驗證
- 使用
X-Sendfile (Apache mod_xsendfile / Nginx X-Accel-Redirect) 卸載 PHP 進程
- 大檔案考慮
readfile() 或 stream_copy_to_stream() 效能更好
- 加入存取控制(權限檢查、防盜鏈)