Recommendation: "PHP Video Tutorial"
1. Principle of resumed transfer at breakpoint
The so-called resumed transfer at breakpoint means Continue downloading from where the file was already downloaded. 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 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
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 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
Use breakpoint resume transmission
GET /down.zip HTTP/1.0 User-Agent: NetFox RANGE: bytes=2000070- Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
There is an extra lineRange: bytes=2000070-
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直接] Range: bytes=startOffset-targetOffset [字节总数也可以去掉]
After the server receives this request, the information returned is as follows:
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
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
The returned code has also been changed to 206 instead of 200.
HTTP/1.1 206 Partial Content
After knowing the above principles, you can program the breakpoint resume download.
2. PHP implementation
/** php下载类,支持断点续传 * download: 下载文件 * setSpeed: 设置下载速度 * getRange: 获取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; // 下载本地文件,获取文件大小 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; } } /** 获取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);
The above is the detailed content of PHP implements breakpoint resume upload of large files. For more information, please follow other related articles on the PHP Chinese website!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

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.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

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

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