Home > php教程 > php手册 > body text

让PHP支持断点续传的源码

WBOY
Release: 2016-06-06 20:33:55
Original
1118 people have browsed it

其实说简单点就是通过这个变量$_SERVER['HTTP_RANGE']取得用户请求的文件的range,然后程序去控制文件的输出。

比如第一次请求一个文件的从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] $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));
}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!