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!

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
