Home Backend Development PHP Tutorial How to resume uploading large files with PHP?

How to resume uploading large files with PHP?

Jun 28, 2020 pm 06:13 PM
php http

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

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/>
Copy after login

The returned code has also been changed to 206 instead of 200.

HTTP/1.1 206 Partial Content<br/>
Copy after login

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=&#39;&#39;, $reload=false){<br/> $fp = @fopen($file, &#39;rb&#39;);<br/> if($fp){<br/> if($name==&#39;&#39;){<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[&#39;Content-Length&#39;];<br/> }<br/> $ranges = $this->getRange($file_size);<br/> $ua = $_SERVER["HTTP_USER_AGENT"];//判断是什么类型浏览器<br/> header(&#39;cache-control:public&#39;);<br/> header(&#39;content-type:application/octet-stream&#39;); <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(&#39;Content-Disposition: attachment; filename="&#39; .$encoded_filename . &#39;"&#39;);<br/> } else if (preg_match("/Firefox/", $ua)) {<br/> header(&#39;Content-Disposition: attachment; filename*="utf8\&#39;\&#39;&#39; . $name . &#39;"&#39;);<br/> }else if (preg_match("/Chrome/", $ua)) {<br/> header(&#39;Content-Disposition: attachment; filename="&#39; . $encoded_filename . &#39;"&#39;);<br/> } else {<br/> header(&#39;Content-Disposition: attachment; filename="&#39; . $name . &#39;"&#39;);<br/> }<br/> //header(&#39;Content-Disposition: attachment; filename="&#39; . $name . &#39;"&#39;);<br/> <br/> if($reload && $ranges!=null){ // 使用续传<br/> header(&#39;HTTP/1.1 206 Partial Content&#39;);<br/> header(&#39;Accept-Ranges:bytes&#39;);<br/> <br/> // 剩余长度<br/> header(sprintf(&#39;content-length:%u&#39;,$ranges[&#39;end&#39;]-$ranges[&#39;start&#39;]));<br/> <br/> // range信息<br/> header(sprintf(&#39;content-range:bytes %s-%s/%s&#39;, $ranges[&#39;start&#39;], $ranges[&#39;end&#39;], $file_size));<br/> //file_put_contents(&#39;test.log&#39;,sprintf(&#39;content-length:%u&#39;,$ranges[&#39;end&#39;]-$ranges[&#39;start&#39;]),FILE_APPEND);<br/> // fp指针跳到断点位置<br/> fseek($fp, sprintf(&#39;%u&#39;, $ranges[&#39;start&#39;]));<br/> }else{<br/> file_put_contents(&#39;test.log&#39;,&#39;2222&#39;,FILE_APPEND);<br/> header(&#39;HTTP/1.1 200 OK&#39;);<br/> header(&#39;content-length:&#39;.$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 &#39;&#39;;<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(&#39;range.log&#39;, json_encode($_SERVER), FILE_APPEND);<br/> if(isset($_SERVER[&#39;HTTP_RANGE&#39;]) && !empty($_SERVER[&#39;HTTP_RANGE&#39;])){<br/> $range = $_SERVER[&#39;HTTP_RANGE&#39;];<br/> $range = preg_replace(&#39;/[\s|,].*/&#39;, &#39;&#39;, $range);<br/> $range = explode(&#39;-&#39;, substr($range, 6));<br/> if(count($range)<2){<br/> $range[1] = $file_size;<br/> }<br/> $range = array_combine(array(&#39;start&#39;,&#39;end&#39;), $range);<br/> if(empty($range[&#39;start&#39;])){<br/> $range[&#39;start&#39;] = 0;<br/> }<br/> if(empty($range[&#39;end&#39;])){<br/> $range[&#39;end&#39;] = $file_size;<br/> }<br/> return $range;<br/> }<br/> return null;<br/> }<br/>}<br/> <br/>$obj = new FileDownload();<br/>$obj->download(&#39;http://down.golaravel.com/laravel/laravel-master.zip&#39;,&#39;&#39;, true);<br/>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

See all articles