HTTP斷點續傳原理是這樣的: http://www.it.com.cn/f/edu/058/17/159759.htmphp
1. 客戶端須要告訴服務器端從哪裏開始。html
2.服務端收到請求,返回206狀態。並標識續傳的起始點及結束點web
以下實例服務器
1. 客戶端傳遞請求信息給web服務器,要求從200070字節開始。。app
GET /down.zip HTTP/1.1url
User-Agent:NetFoxcode
RANGE: bytes = 200070-htm
Accept:text/html,image/gif,image/jpeg,*;q=.2,*/*;q=.2ip
2.服務端收到這個請求之後,返回信息web服務器
206
Content-Length = 100222222
Content-Range = bytes 200070 - 100222221/100222222
Content-Type=application/octet-stream
注意:服務端狀態 206; Content-Range = bytes (客戶端請求續傳起始點) - (下載文件大小-1)/(下載文件大小)
在PHP中,是利用$_SERVER['HTTP-RANGE']來取得客戶端請求的續傳起始點。因此其實現代碼以下
<?php
/**
* PHP-HTTP斷點續傳實現
* @param string $path: 文件所在路徑
* @param string $file: 文件名
* @return void
*/
function download($path,$file) {
$real = $path.'/'.$file;
if(!file_exists($real)) {
return false;
}
$size = filesize($real);
$range = 0;
if(isset($_SERVER['HTTP_RANGE'])) {
header('HTTP /1.1 206 Partial Content');
$range = str_replace('=','-',$_SERVER['HTTP_RANGE']);
$range = explode('-',$range);
$range = trim($range[1]);
$size2 = $size-1;
header('Content-Length:'.$size);
header('Content-Range: bytes '.$range.'-'.$size2.'/'.$size);
} else {
header('Content-Length:'.$size);
header('Content-Range: bytes 0-'.$size2.'/'.$size);
}
header('Accenpt-Ranges: bytes');
header('application/octet-stream');
header("Cache-control: public");
header("Pragma: public");
$ua = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/MISE/',$ua)) {
$ie_filename = str_replace('+','%20',urlencode($file));
header('Content-Dispositon:attachment; filename='.$ie_filename);
} else {
header('Content-Dispositon:attachment; filename='.$file);
}
$fp = fopen($real,'rb+');
fseek($fp,$range);
while(!feof($fp)) {
set_time_limit(0);
print(fread($fp,1024));
flush();
ob_flush();
}
fclose($fp);
}
?>