search
HomeBackend DevelopmentPHP TutorialImplemented file download php class that supports breakpoint resume transfer

This article describes the file download class implemented by PHP that supports breakpoint resume download and its usage. It is a very practical technique. Share it with everyone for your reference. The specific method is as follows:

Generally speaking, PHP supports breakpoint resumption, mainly relying on the header HTTP_RANGE in the HTTP protocol.

HTTP breakpoint resumption principle:

Http header Range, Content-Range()
Range and Content-Range entity headers are generally used in HTTP headers only for breakpoint downloads.
In the Range user request header, specify the position of the first byte and the last byte. The position like (Range: 200-300)
Content-Range is used for the response header

Request to download the entire file:

GET /test.rar HTTP/1.1
Connection: close
Host: 116.1.219.219
Range: bytes=0-801 //General request to download the entire file is bytes=0- or do not use this header

Normal response:

HTTP/1.1 200 OK
Content-Length: 801
Content-Type: application/octet-stream
Content-Range: bytes 0-800/801 //801: Total file size

FileDownload.class.php class file code is as follows:

  1. /**
  2. * Download class, supports resumed downloads
  3. * @time: 2015 06 30 09:36
  4. * @author:guoyu@xzdkiosk.com
  5. * PHP download class, supports resumed downloads
  6. * Func:
  7. * download: Download file
  8. * setSpeed: Set the download speed
  9. * getRange: Get the Range in the header
  10. */
  11. class FileDownload{ // class start
  12. private $_speed = 512; // Download speed
  13. /**Download
  14. * @param String $file The path of the file to be downloaded
  15. * @param String $name The file name, if it is empty, it will be the same as the downloaded file name
  16. * @param boolean $reload Whether to enable breakpoint resumption
  17. */
  18. public function download($file, $name='', $reload=false){
  19. if(file_exists($file)){
  20. if($name=='') {
  21. $name = basename($file);
  22. }
  23. $fp = fopen($file, 'rb');
  24. $file_size = filesize($file);
  25. $ranges = $this->getRange($ file_size);
  26. header('cache-control:public');
  27. header('content-type:application/octet-stream');
  28. header('content-disposition:attachment; filename='.$name);
  29. if($reload && $ranges!=null){ // Use resume
  30. header('HTTP/1.1 206 Partial Content');
  31. header('Accept-Ranges:bytes');
  32. // Remaining length
  33. header(sprintf('content-length:%u',$ranges['end']-$ranges['start']));
  34. // range information
  35. header(sprintf('content-range:bytes % s-%s/%s', $ranges['start'], $ranges['end'], $file_size));
  36. // The fp pointer jumps to the breakpoint position
  37. fseek($fp, sprintf(' %u', $ranges['start']));
  38. }else{
  39. header('HTTP/1.1 200 OK');
  40. header('content-length:'.$file_size);
  41. }
  42. while( !feof($fp)){
  43. echo fread($fp, round($this->_speed*1024,0));
  44. ob_flush();
  45. //sleep(1); // For testing, minus Slow download speed
  46. }
  47. ($fp!=null) && fclose($fp);
  48. }else{
  49. return '';
  50. }
  51. }
  52. /**Set download speed
  53. * @param int $speed
  54. */
  55. public function setSpeed( $speed){
  56. if(is_numeric($speed) && $speed>16 && $speed $this->_speed = $speed;
  57. }
  58. }
  59. /**Get header range information
  60. * @param int $file_size file size
  61. * @return Array
  62. */
  63. private function getRange($file_size){
  64. if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])){
  65. $range = $_SERVER['HTTP_RANGE'];
  66. $range = preg_replace('/[s|,].*/', '', $range);
  67. $range = explode('-', substr($range, 6));
  68. if(count($range)< ;2){
  69. $range[1] = $file_size;
  70. }
  71. $range = array_combine(array('start','end'), $range);
  72. if(empty($range['start']) ){
  73. $range['start'] = 0;
  74. }
  75. if(empty($range['end'])){
  76. $range['end'] = $file_size;
  77. }
  78. return $range;
  79. }
  80. return null;
  81. }
  82. } // class end
  83. ?>
Copy code

The demo code is as follows:
  1. require('FileDownload.class.php');
  2. $file = 'book.zip';
  3. $name = time().'.zip';
  4. $obj = new FileDownload();
  5. $flag = $obj->download($file, $name);
  6. //$flag = $obj->download($file, $name, true); // Resume upload from breakpoint
  7. if(!$flag){
  8. echo 'file not exists';
  9. }
  10. ?>
Copy code

Test method for resumable download:

Use the linux wget command to test the download, wget -c -O file http://xxx

1. Turn off breakpoint resumption first

  1. $flag = $obj->download($file, $name);
Copy code

  1. test@ubuntu:~/Downloads$ wget -O test.rar http://demo.test.com/demo.php
  2. --2013-06-30 16:52:44-- http:/ /demo.test.com/demo.php
  3. Resolving host demo.test.com... 127.0.0.1
  4. Connecting demo.test.com|127.0.0.1|:80... Connected.
  5. HTTP request sent, waiting for response... 200 OK
  6. Length: 10445120 (10.0M) [application/octet-stream]
  7. Saving to: “test.rar”
  8. 30% [====== ======================> ] 3,146,580 513K/s Estimated time 14s
  9. ^C
  10. test@ubuntu:~/Downloads$ wget -c -O test .rar http://demo.test.com/demo.php
  11. --2013-06-30 16:52:57-- http://demo.test.com/demo.php
  12. Resolving host demo.test .com... 127.0.0.1
  13. Connecting demo.test.com|127.0.0.1|:80... Connected.
  14. HTTP request sent, waiting for response... 200 OK
  15. Length: 10445120 (10.0M) [application/octet-stream]
  16. Saving to: “test.rar”
  17. 30% [======== =====================> ] 3,146,580 515K/s Estimated time 14s
  18. ^C
Copy code

You can see that wget -c cannot resume the upload

2. Enable breakpoint resumption

  1. $flag = $obj->download($file, $name, true);
Copy code

  1. test@ubuntu:~/Downloads$ wget -O test.rar http://demo.test.com/demo.php
  2. --2013-06-30 16:53:19-- http:/ /demo.test.com/demo.php
  3. Resolving host demo.test.com... 127.0.0.1
  4. Connecting demo.test.com|127.0.0.1|:80... Connected.
  5. HTTP request sent, waiting for response... 200 OK
  6. Length: 10445120 (10.0M) [application/octet-stream]
  7. Saving to: “test.rar”
  8. 20% [====== ============> ] 2,097,720 516K/s Estimated time 16s
  9. ^C
  10. test@ubuntu:~/Downloads$ wget -c -O test.rar http://demo.test. com/demo.php
  11. --2013-06-30 16:53:31-- http://demo.test.com/demo.php
  12. Resolving host demo.test.com... 127.0.0.1
  13. Resolving Connect demo.test.com|127.0.0.1|:80... Connected.
  14. HTTP request sent, waiting for response... 206 Partial Content
  15. Length: 10445121 (10.0M), 7822971 (7.5M) Bytes remaining [application/octet-stream]
  16. Saving to: “test.rar”
  17. 100%[++++++++++++++++++++++++====================== ================================================== ]
  18. You can see that the download will start from the breakpoint position (%20).
From: http://blog.csdn.net/phpfenghuo/article/details/46691865

Resume upload from breakpoint, php


Statement
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)