首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP HTTP 下載類支援斷點續傳(Range 請求處理)

     編輯:PHP 綜合知識

簡易使用方式

<?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)

多種資料源

  1. 本地檔案 (data_type = 0):fopen('rb') + fread()
  2. 記憶體字串 (data_type = 1):substr() 切片輸出
  3. 外部重導向 (data_type = 2):header('Location: ...')

生產環境建議

  • 加入 ETag / Last-Modified 快取驗證
  • 使用 X-Sendfile (Apache mod_xsendfile / Nginx X-Accel-Redirect) 卸載 PHP 進程
  • 大檔案考慮 readfile() 或 stream_copy_to_stream() 效能更好
  • 加入存取控制(權限檢查、防盜鏈)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved