How to resume uploading large files with PHP?
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
