PHP斷點續傳的原理與實現
斷點續傳主要是HTTP協議中的Content-Range前序。其理解如下:
Content-Range:響應資源的範圍。可以在多次請求中標記請求的資源範圍,在串連斷開重新串連時,用戶端只請求該資源未被下載的部分,而不是重新請求整個資源,實現了斷點續傳。迅雷就是基於這個原理,使用多線程分段讀取網路上的資源,最後合并。關於PHP使用多線程實現斷點續傳稍後討論。本文只實現簡單的斷點續傳。
代碼實現:
先定義一個函數 getRange() 這個函數用來處理 header中 Range 具體資料的處理
/** $file_size 檔案大小 */ functiongetRange($file_size){ $range =isset($_SERVER['HTTP_RANGE'])?$_SERVER['HTTP_RANGE']:null; if(!empty($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 (!isset($range['end']) || empty($range['end'])) { $range['end'] = $file_size; } return$range; } return null; }
假設檔案的地址為 $file_path
$speed = 512;//此參數為下載最大速度 $pos =strrpos($file_path, "/"); $file_name =substr($file_path, $pos+1); $file_size =filesize($file_path); $ranges =getRange($file_size); $fh = fopen($file_path, "rb"); header('Cache-control: public'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.$file_name); if ($ranges !=null) { header('HTTP/1.1 206 Partial Content'); header('Accept-Ranges: bytes'); header(sprintf('Content-Length: %u',$ranges['end'] - $ranges['start'])); header(sprintf('Content-Range: bytes %s-%s/%s', $ranges['start'],$ranges['end'], $file_size)); fseek($fh,sprintf('%u',$ranges['start'])); }else{ header("HTTP/1.1 200 OK"); header(sprintf('Content-Length:%s', $file_size)); } while(!feof($fh)) { echo fread($fh, round($speed*1024, 0)); ob_flush(); sleep(1); } ($fh != null)&& fclose($fh);
文章參考自:http://www.cnblogs.com/xyxiong/archive/2011/02/16/1956167.html