1. Principle of resumable download
The so-called resumable download means that the file must be downloaded from where to continue downloading. Breakpoints were not supported in previous versions of the HTTP protocol, but have been supported since HTTP/1.1. Generally, the Range and Content-Range entity headers are only used for breakpoint downloading.
Do not use breakpoint resumption
get /down.zip http/1.1<br/>accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-<br/>excel, application/msword, application/vnd.ms-powerpoint, */*<br/>accept-language: zh-cn<br/>accept-encoding: gzip, deflate<br/>user-agent: mozilla/4.0 (compatible; msie 5.01; windows nt 5.0)<br/>connection: keep-alive<br/>
After the server receives the request, it searches for the requested file as required, extracts the file information, and then returns it to the browser. The return information is as follows:
HTTP/1.1 200 Ok<br/>content-length=106786028<br/>accept-ranges=bytes<br/>date=mon, 30 apr 2001 12:56:11 gmt<br/>etag=w/"02ca57e173c11:95b"<br/>content-type=application/octet-stream<br/>server=microsoft-iis/5.0<br/>last-modified=mon, 30 apr 2001 12:56:11 gmt<br/>
Use breakpoint resume transmission
GET /down.zip HTTP/1.0<br/>User-Agent: NetFox<br/>RANGE: bytes=2000070-<br/>Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2<br/>
There is an extra lineRange: bytes=2000070-<br>
This line means to tell the server to down. The zip file is transmitted starting from 2000070 bytes, and the previous bytes do not need to be transmitted. The complete format of
Range is:
Range: bytes=startOffset-targetOffset/sum [表示从startOffset读取,一直读取到targetOffset位置,读取总数为sum直接]<br/> <br/>Range: bytes=startOffset-targetOffset [字节总数也可以去掉]<br/>
After the server receives this request, the information returned is as follows:
HTTP/1.1 206 Partial Content<br/>content-length=106786028<br/>content-range=bytes 2000070-106786027/106786028<br/>date=mon, 30 apr 2001 12:55:20 gmt<br/>etag=w/"02ca57e173c11:95b"<br/>content-type=application/octet-stream<br/>server=microsoft-iis/5.0<br/>last-modified=mon, 30 apr 2001 12:55:20 gmt<br/>
Compare it with the information returned by the previous server, and you will find that an extra line has been added. :
Content-Range=bytes 2000070-106786027/106786028<br/>
The returned code has also been changed to 206 instead of 200.
HTTP/1.1 206 Partial Content<br/>
After knowing the above principles, you can program the breakpoint resume download.
2. PHP implementation
/** php下载类,支持断点续传<br/> * download: 下载文件<br/> * setSpeed: 设置下载速度<br/> * getRange: 获取header中Range<br/> */<br/> <br/>class FileDownload{<br/> <br/> /** 下载<br/> * @param String $file 要下载的文件路径<br/> * @param String $name 文件名称,为空则与下载的文件名称一样<br/> * @param boolean $reload 是否开启断点续传<br/> */<br/> public function download($file, $name='', $reload=false){<br/> $fp = @fopen($file, 'rb');<br/> if($fp){<br/> if($name==''){<br/> $name = basename($file);<br/> }<br/> $header_array = get_headers($file, true);<br/> //var_dump($header_array);die;<br/> // 下载本地文件,获取文件大小<br/> if (!$header_array) {<br/> $file_size = filesize($file);<br/> } else {<br/> $file_size = $header_array['Content-Length'];<br/> }<br/> $ranges = $this->getRange($file_size);<br/> $ua = $_SERVER["HTTP_USER_AGENT"];//判断是什么类型浏览器<br/> header('cache-control:public');<br/> header('content-type:application/octet-stream'); <br/> <br/> $encoded_filename = urlencode($name);<br/> $encoded_filename = str_replace("+", "%20", $encoded_filename);<br/> <br/> //解决下载文件名乱码<br/> if (preg_match("/MSIE/", $ua) || preg_match("/Trident/", $ua) ){ <br/> header('Content-Disposition: attachment; filename="' .$encoded_filename . '"');<br/> } else if (preg_match("/Firefox/", $ua)) {<br/> header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');<br/> }else if (preg_match("/Chrome/", $ua)) {<br/> header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');<br/> } else {<br/> header('Content-Disposition: attachment; filename="' . $name . '"');<br/> }<br/> //header('Content-Disposition: attachment; filename="' . $name . '"');<br/> <br/> if($reload && $ranges!=null){ // 使用续传<br/> header('HTTP/1.1 206 Partial Content');<br/> header('Accept-Ranges:bytes');<br/> <br/> // 剩余长度<br/> header(sprintf('content-length:%u',$ranges['end']-$ranges['start']));<br/> <br/> // range信息<br/> header(sprintf('content-range:bytes %s-%s/%s', $ranges['start'], $ranges['end'], $file_size));<br/> //file_put_contents('test.log',sprintf('content-length:%u',$ranges['end']-$ranges['start']),FILE_APPEND);<br/> // fp指针跳到断点位置<br/> fseek($fp, sprintf('%u', $ranges['start']));<br/> }else{<br/> file_put_contents('test.log','2222',FILE_APPEND);<br/> header('HTTP/1.1 200 OK');<br/> header('content-length:'.$file_size);<br/> }<br/> <br/> while(!feof($fp)){<br/> //echo fread($fp, round($this->_speed*1024,0));<br/> //echo fread($fp, $file_size);<br/> echo fread($fp, 4096);<br/> ob_flush();<br/> }<br/> <br/> ($fp!=null) && fclose($fp);<br/> }else{<br/> return '';<br/> }<br/> }<br/> <br/> /** 设置下载速度<br/> * @param int $speed<br/> */<br/> public function setSpeed($speed){<br/> if(is_numeric($speed) && $speed>16 && $speed<4096){<br/> $this->_speed = $speed;<br/> }<br/> }<br/> <br/> /** 获取header range信息<br/> * @param int $file_size 文件大小<br/> * @return Array<br/> */<br/> private function getRange($file_size){<br/> //file_put_contents('range.log', json_encode($_SERVER), FILE_APPEND);<br/> if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])){<br/> $range = $_SERVER['HTTP_RANGE'];<br/> $range = preg_replace('/[\s|,].*/', '', $range);<br/> $range = explode('-', substr($range, 6));<br/> if(count($range)<2){<br/> $range[1] = $file_size;<br/> }<br/> $range = array_combine(array('start','end'), $range);<br/> if(empty($range['start'])){<br/> $range['start'] = 0;<br/> }<br/> if(empty($range['end'])){<br/> $range['end'] = $file_size;<br/> }<br/> return $range;<br/> }<br/> return null;<br/> }<br/>}<br/> <br/>$obj = new FileDownload();<br/>$obj->download('http://down.golaravel.com/laravel/laravel-master.zip','', true);<br/>
Recommended tutorial: "PHP"
The above is the detailed content of How to resume uploading large files with PHP?. For more information, please follow other related articles on the PHP Chinese website!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),