欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

让PHP支持断点续传的源码

程序员文章站 2022-06-03 10:21:14
比如第一次请求一个文件的从0到999字节,第二次请求1000到1999字节,以此类推,每次请求1000字节的内容,然后程序通过fseek函数去取得对应的文件位置,然后输出。...
比如第一次请求一个文件的从0到999字节,第二次请求1000到1999字节,以此类推,每次请求1000字节的内容,然后程序通过fseek函数去取得对应的文件位置,然后输出。
复制代码 代码如下:

$fname = './05e58c19552bb26b158f6621a6650899';
$fp = fopen($fname,'rb');
$fsize = filesize($fname);
if (isset($_server['http_range']) && ($_server['http_range'] != "") && preg_match("/^bytes=([0-9]+)-$/i", $_server['http_range'], $match) && ($match[1] < $fsize)) {
$start = $match[1];
} else {
$start = 0;
}
@header("cache-control: public");
@header("pragma: public");
if ($start > 0) {
fseek($fp, $start);
header("http/1.1 206 partial content");
header("content-length: " . ($fsize - $start));
header("content-ranges: bytes" . $start . "-" . ($fsize - 1) . "/" . $fsize);
} else {
header("content-length: $fsize");
header("accept-ranges: bytes");
}
@header("content-type: application/octet-stream");
@header("content-disposition: attachment;filename=1.rm");
fpassthru($fp);

大家也可以看下discuz!论坛软件的attachment.php文件是如何实现断点续传的。请看代码:

也是通过$_server['http_range']取得用户请求的文件的range,具体的大家可以查看其源码分析下。这里我就当抛砖引玉了。
复制代码 代码如下:

$range = 0;
if($readmod == 4) {
dheader('accept-ranges: bytes');
if(!emptyempty($_server['http_range'])) {
list($range) = explode('-',(str_replace('bytes=', '', $_server['http_range'])));
$rangesize = ($filesize - $range) > 0 ? ($filesize - $range) : 0;
dheader('content-length: '.$rangesize);
dheader('http/1.1 206 partial content');
dheader('content-range: bytes='.$range.'-'.($filesize-1).'/'.($filesize));
}
}