實現的支持斷點續傳的文件下載php類

jopen 10年前發布 | 4K 次閱讀 PHP

本文實例講述了php實現的支持斷點續傳的文件下載類及其用法,是非常實用的技巧。分享給大家供大家參考。具體方法如下:

通常來說,php支持斷點續傳,主要依靠HTTP協議中 header HTTP_RANGE實現。

HTTP斷點續傳原理:

Http頭 Range、Content-Range()
HTTP頭中一般斷點下載時才用到Range和Content-Range實體頭,
Range用戶請求頭中,指定第一個字節的位置和最后一個字節的位置,如(Range:200-300)
Content-Range用于響應頭

請求下載整個文件:

GET /test.rar HTTP/1.1
Connection: close
Host: 116.1.219.219
Range: bytes=0-801 //一般請求下載整個文件是bytes=0- 或不用這個頭

一般正常回應:

HTTP/1.1 200 OK
Content-Length: 801     
Content-Type: application/octet-stream
Content-Range: bytes 0-800/801 //801:文件總大小

FileDownload.class.php類文件代碼如下:

    <?php
/**

 * 下載類,支持斷點續傳 
 * @time : 2015 06 30 09:36 
 * @author:guoyu@xzdkiosk.com 
 * php下載類,支持斷點續傳 
 * Func: 
 * download: 下載文件 
 * setSpeed: 設置下載速度 
 * getRange: 獲取header中Range 
 */  

class FileDownload{ // class start   

  private $_speed = 512;  // 下載速度   

  /** 下載  
  * @param String $file  要下載的文件路徑  
  * @param String $name  文件名稱,為空則與下載的文件名稱一樣  
  * @param boolean $reload 是否開啟斷點續傳  
  */  
  public function download($file, $name='', $reload=false){   
    if(file_exists($file)){   
      if($name==''){   
        $name = basename($file);   
      }   

      $fp = fopen($file, 'rb');   
      $file_size = filesize($file);   
      $ranges = $this->getRange($file_size);   

      header('cache-control:public');   
      header('content-type:application/octet-stream');   
      header('content-disposition:attachment; filename='.$name);   

      if($reload && $ranges!=null){ // 使用續傳   
        header('HTTP/1.1 206 Partial Content');   
        header('Accept-Ranges:bytes');   

        // 剩余長度   
        header(sprintf('content-length:%u',$ranges['end']-$ranges['start']));   

        // range信息   
        header(sprintf('content-range:bytes %s-%s/%s', $ranges['start'], $ranges['end'], $file_size));   

        // fp指針跳到斷點位置   
        fseek($fp, sprintf('%u', $ranges['start']));   
      }else{   
        header('HTTP/1.1 200 OK');   
        header('content-length:'.$file_size);   
      }   

      while(!feof($fp)){   
        echo fread($fp, round($this->_speed*1024,0));   
        ob_flush();   
        //sleep(1); // 用于測試,減慢下載速度   
      }   

      ($fp!=null) && fclose($fp);   

    }else{   
      return '';   
    }   
  }   

  /** 設置下載速度  
  * @param int $speed  
  */  
  public function setSpeed($speed){   
    if(is_numeric($speed) && $speed>16 && $speed<4096){   
      $this->_speed = $speed;   
    }   
  }   

  /** 獲取header range信息  
  * @param int  $file_size 文件大小  
  * @return Array  
  */  
  private function getRange($file_size){   
    if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])){   
      $range = $_SERVER['HTTP_RANGE'];   
      $range = preg_replace('/[\s|,].*/', '', $range);   
      $range = explode('-', substr($range, 6));   
      if(count($range)<2){   
        $range[1] = $file_size;   
      }   
      $range = array_combine(array('start','end'), $range);   
      if(empty($range['start'])){   
        $range['start'] = 0;   
      }   
      if(empty($range['end'])){   
        $range['end'] = $file_size;   
      }   
      return $range;   
    }   
    return null;   
  }   
} // class end   

?>   </pre> 


demo示例代碼如下:

    <?php
require('FileDownload.class.php');
$file = 'book.zip';
$name = time().'.zip';
$obj = new FileDownload();
$flag = $obj->download($file, $name);
//$flag = $obj->download($file, $name, true); // 斷點續傳

if(!$flag){   
  echo 'file not exists';   
}   
?>  </pre> 


斷點續傳測試方法:

使用linux wget命令去測試下載, wget -c -O file http://xxx

1.先關閉斷點續傳

    $flag = $obj->download($file, $name);  

    test@ubuntu:~/Downloads$ wget -O test.rar http://demo.test.com/demo.php
--2013-06-30 16:52:44-- http://demo.test.com/demo.php
正在解析主機 demo.test.com... 127.0.0.1
正在連接 demo.test.com|127.0.0.1|:80... 已連接。
已發出 HTTP 請求,正在等待回應... 200 OK
長度: 10445120 (10.0M) [application/octet-stream]
正在保存至: “test.rar”

30% [============================>                                   ] 3,146,580  513K/s 估時 14s   
^C   
test@ubuntu:~/Downloads$ wget -c -O test.rar http://demo.test.com/demo.php   
--2013-06-30 16:52:57-- http://demo.test.com/demo.php   
正在解析主機 demo.test.com... 127.0.0.1   
正在連接 demo.test.com|127.0.0.1|:80... 已連接。   
已發出 HTTP 請求,正在等待回應... 200 OK   
長度: 10445120 (10.0M) [application/octet-stream]   
正在保存至: “test.rar”   
30% [============================>                                   ] 3,146,580  515K/s 估時 14s   
^C   </pre> 


可以看到,wget -c不能斷點續傳 

2.開啟斷點續傳

    $flag = $obj->download($file, $name, true);  

    test@ubuntu:~/Downloads$ wget -O test.rar http://demo.test.com/demo.php
--2013-06-30 16:53:19-- http://demo.test.com/demo.php
正在解析主機 demo.test.com... 127.0.0.1
正在連接 demo.test.com|127.0.0.1|:80... 已連接。
已發出 HTTP 請求,正在等待回應... 200 OK
長度: 10445120 (10.0M) [application/octet-stream]
正在保存至: “test.rar”

20% [==================>                                        ] 2,097,720  516K/s 估時 16s   
^C   
test@ubuntu:~/Downloads$ wget -c -O test.rar http://demo.test.com/demo.php   
--2013-06-30 16:53:31-- http://demo.test.com/demo.php   
正在解析主機 demo.test.com... 127.0.0.1   
正在連接 demo.test.com|127.0.0.1|:80... 已連接。   
已發出 HTTP 請求,正在等待回應... 206 Partial Content   
長度: 10445121 (10.0M),7822971 (7.5M) 字節剩余 [application/octet-stream]   
正在保存至: “test.rar”   

100%[++++++++++++++++++++++++=========================================================================>] 10,445,121  543K/s  花時 14s     

2013-06-30 16:53:45 (543 KB/s) - 已保存 “test.rar” [10445121/10445121])   </pre> 


可以看到會從斷點的位置(%20)開始下載。

來自:http://blog.csdn.net/phpfenghuo/article/details/46691865

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!