PHP support for the continuation of a breakpoint file download class

Source: Internet
Author: User
Tags php download ranges rar
PHP supports the continuation of breakpoints, mainly rely on the HTTP protocol header Http_range implementation.

HTTP Breakpoint Continuation principle
HTTP header Range, Content-range ()
The range and Content-range entity headers are used in HTTP headers for general breakpoint downloads.
Range user Request header, specify the position of the first byte and the position of the last byte, such as (range:200-300)
Content-range for response headers

Request to download the entire file:
Get/test.rar http/1.1
Connection:close
host:116.1.219.219
range:bytes=0-801//General request to download the entire file is bytes=0-or without this header

General Normal response
http/1.1 OK
content-length:801
Content-type:application/octet-stream
Content-range:bytes 0-800/801//801: Total File size

FileDownload.class.php

<?php/** PHP Download class, support breakpoint continuation * date:2013-06-30* author:fdipzone* ver:1.0** func:* Download: Download file * setspeed   : Set Download speed * GetRange: Get header in Range*/class filedownload{//class start Private $_speed = 512; Download speed/** Download * @param string $file file path to download * @param string $name file name, empty is the same as the downloaded file name * @param boolean            $reload whether to turn on the breakpoint continuation */Public function Download ($file, $name = ", $reload =false) {if (file_exists ($file)) {            if ($name = = ") {$name = basename ($file);            } $fp = fopen ($file, ' RB ');            $file _size = filesize ($file);            $ranges = $this->getrange ($file _size);            Header (' Cache-control:public ');            Header (' Content-type:application/octet-stream ');            Header (' content-disposition:attachment; Filename= '. $name);                if ($reload && $ranges!=null) {//Use continuation header (' http/1.1 206 Partial Content '); Header (' accept-ranges:bytes ');                                Remaining Length header (sprintf (' content-length:%u ', $ranges [' End ']-$ranges [' Start ']                                );                                Range Information Header (sprintf (' Content-range:bytes%s-%s/%s ', $ranges [' Start '], $ranges [' End '], $file _size));            The FP pointer jumps to the breakpoint position fseek ($fp, sprintf ('%u ', $ranges [' Start ']);                }else{header (' http/1.1 OK ');            Header (' Content-length: '. $file _size);                } while (!feof ($fp)) {echo fread ($fp, round ($this->_speed*1024,0));                Ob_flush (); Sleep (1);        For testing, slowing download speed} ($fp!=null) && fclose ($FP);        }else{return '; }}/** set download speed * @param int $speed */Public Function setspeed ($speed) {if (Is_numeric ($speed) && Amp        $speed >16 && $speed <4096) {$this->_speed = $speed; }    }    /** Get Header Range Info * @param int $file _size File size * @return Array */Private Function GetRange ($file _size) { 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; }}//Class end?>

Demo

<?phprequire (' FileDownload.class.php '); $file = ' book.zip '; $name = time (). Zip '; $obj = new FileDownload (); $flag = $obj->download ($file, $name);//$flag = $obj->download ($file, $name, true); Breakpoint Continuation if (! $flag) {    echo ' file not exists ';}? >

Test methods for the continuation of breakpoints:
Use the Linux wget command to test the download, wget-c-o file http://www.php.cn/

1. Turn off the continuation of the breakpoint first
$flag = $obj->download ($file, $name);

fdipzone@ubuntu:~/downloads$ wget-o Test.rar http://www.php.cn/--2013-06-30 16:52:44--http://www.php.cn/parsing host demo.fdipzone.com ... 127.0.0.1 Connecting demo.fdipzone.com|127.0.0.1|:80 ... is connected. An HTTP request has been made and is waiting for a response ...                                                                     $ OK Length: 10445120 (10.0M) [Application/octet-stream] saving to: "Test.rar" 30% [============================> ] 3,146,580 513k/s Estimated time 14s^cfdipzone@ubuntu:~/downloads$ wget-c -O test.rar http://www.php.cn/--2013-06-30 16:52:57--http://www.php.cn/parsing host demo.fdipzone.com ... 127.0.0.1 Connecting demo.fdipzone.com|127.0.0.1|:80 ... is connected. An HTTP request has been made and is waiting for a response ...                                                                     $ OK Length: 10445120 (10.0M) [Application/octet-stream] saving to: "Test.rar" 30% [============================> ] 3,146,580 515k/s estimate when 14s^c can see, wget-c cannot continue to pass the breakpoint 


2. Turn on breakpoint continuation
$flag = $obj->download ($file, $name, true );

fdipzone@ubuntu:~/downloads$ wget-o test.rar http://www.php.cn/--2013-06-30 16:53:19--http://www.php.cn/Parsing host Demo.fdipzone.com ... 127.0.0.1 Connecting demo.fdipzone.com|127.0.0.1|:80 ... is connected. An HTTP request has been made and is waiting for a response ...                                                                               $ OK Length: 10445120 (10.0M) [Application/octet-stream] saving to: "Test.rar" 20% [==================> ] 2,097,720 516k/s Estimated time 16s^cfdipzone@ubuntu:~/downloads$ wget-c -O test.rar http://www.php.cn/--2013-06-30 16:53:31--http://www.php.cn/parsing host demo.fdipzone.com ... 127.0.0.1 Connecting demo.fdipzone.com|127.0.0.1|:80 ... is connected. An HTTP request has been made and is waiting for a response ... 206 Partial Content Length: 10445121 (10.0M), 7822971 (7.5M) bytes remaining [Application/octet-stream] saving to: "Test.rar" 100%[++++++++++ ++++++++++++++=========================================================================>] 10,445,121 543K/s Flower 14s 2013-06-30 16:53:45 (543 kb/s)-Saved "Test.rar" [10445121/10445121]) you can see that the download starts at the location of the breakpoint (%20).


The above is the PHP support for the continuation of the file download class content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.