PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php实现断点续传大文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

PHP实现断点续传大文件

一、断点续传原理

所谓断点续传,也就是要从文件已经下载的地方开始继续下载。在以前版本的 http 协议是不支持断点的,http/1.1 开始就支持了。一般断点下载时才用到 Range 和 Content-Range 实体头。

不使用断点续传

get /down.zip http/1.1
accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
accept-language: zh-cn
accept-encoding: gzip, deflate
user-agent: mozilla/4.0 (compatible; msie 5.01; windows nt 5.0)
connection: keep-alive

 服务器收到请求后,按要求寻找请求的文件提取文件的信息,然后返回给浏览器,返回信息如下:

http/1.1 200 Ok
content-length=106786028
accept-ranges=bytes
date=mon, 30 apr 2001 12:56:11 gmt
etag=w/"02ca57e173c11:95b"
content-type=application/octet-stream
server=microsoft-iis/5.0
last-modified=mon, 30 apr 2001 12:56:11 gmt

 使用断点续传

GET /down.zip http/1.0
User-Agent: NetFox
RANGE: bytes=2000070-
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

 多了这么一行Range: bytes=2000070-
这一行的意思就是告诉服务器down.zip这个文件2000070字节开始传,前面的字节不用传了。
Range的完整格式是:

Range: bytes=startOffset-targetOffset/sum  [表示从startOffset读取,一直读取到targetOffset位置,读取总数为sum直接]

Range: bytes=startOffset-targetOffset  [字节总数也可以去掉]

 服务器收到这个请求以后,返回的信息如下:

http/1.1 206 Partial Content
content-length=106786028
content-range=bytes 2000070-106786027/106786028
date=mon, 30 apr 2001 12:55:20 gmt
etag=w/"02ca57e173c11:95b"
content-type=application/octet-stream
server=microsoft-iis/5.0
last-modified=mon, 30 apr 2001 12:55:20 gmt

 和前面服务器返回的信息比较一下,@R_219_10585@增加了一行:

Content-Range=bytes 2000070-106786027/106786028

 返回的代码也改为206了,而不再是200了。

http/1.1 206 Partial Content

 

知道了以上原理,就可以进行断点续传的编程了。

二、PHP实现

/**  PHP下载类,支持断点续传
 *   download: 下载文件
 *   setSpeed: 设置下载速度
 *   getRange: @L_607_16@header中Range
 */

class FileDownload{

    /** 下载
     * @param String  $file   要下载的文件路径
     * @param String  $name   文件名称,为空则与下载的文件名称一样
     * @param Boolean $reload 是否开启断点续传
     */
    public function download($file, $name='', $reload=falsE){
        $fp = @fopen($file, 'rb');
        if($fp){
            if($name==''){
                $name = basename($filE);
            }
            $header_array = get_headers($file, truE);
            //var_dump($header_array);die;
            // 下载本地文件,@L_607_16@文件大小
            if (!$header_array) {
                $file_size = filesize($filE);
            } else {
                $file_size = $header_arraY['Content-Length'];
            }
            $ranges = $this->getRange($file_sizE);
            $ua = $_SERVER["http_user_ageNT"];//判断是什么类型浏览器
            header('cache-control:public');
            header('content-type:application/octet-stream');    

            $encoded_filename = urlencode($Name);
            $encoded_filename = str_replace("+", "%20", $encoded_fileName);

            //解决下载文件名乱码
            if (preg_match("/MSIE/", $ua) ||  preg_match("/Trident/", $ua) ){               
                header('Content-Disposition: attachment; filename="' .$encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');
            }else if (preg_match("/Chrome/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $name . '"');
            }
            //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));
                //file_put_contents('test.log',sprintf('content-length:%u',$ranges['end']-$ranges['start']),FILE_APPEND);
                // fp指针跳到断点位置
                fseek($fp, sprintf('%u', $ranges['start']));
            }else{
                file_put_contents('test.log','2222',FILE_APPEND);
                header('http/1.1 200 OK');
                header('content-length:'.$file_sizE);
            }

            while(!feof($fp)){
                //echo fread($fp, round($this->_speed*1024,0));
                //echo fread($fp, $file_sizE);
                echo fread($fp, 4096);
                ob_flush();
            }

            ($fp!=null) && fclose($fp);
        }else{
            return '';
        }
    }

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

    /** @L_607_16@header range信息
     * @param  int   $file_size 文件大小
     * @return Array
     */
    private function getRange($file_sizE){
        //file_put_contents('range.log', json_encode($_SERVER), FILE_APPEND);
        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;
    }
}

$obj = new FileDownload();
$obj->download('http://down.golaravel.com/laravel/laravel-master.zip','', truE);

 


大佬总结

以上是大佬教程为你收集整理的php实现断点续传大文件全部内容,希望文章能够帮你解决php实现断点续传大文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: