Home Backend Development PHP Tutorial PHP download remote file class that supports breakpoint resume download

PHP download remote file class that supports breakpoint resume download

Jul 25, 2016 am 08:44 AM

PHP download remote file class, supports breakpoint resume download, and the code contains specific calling instructions. The program mainly uses the HTTP protocol to download files. The HTTP1.1 protocol must specify that the link should be closed after the document ends. Otherwise, feof cannot be used to judge the end when reading the document. There are two ways to use it. Please download and view the source code for details.

  1. /**
  2. * Downloading remote files supports breakpoint resumption
  3. */
  4. class HttpDownload {
  5. private $m_url = "";
  6. private $m_urlpath = "";
  7. private $m_scheme = "http";
  8. private $m_host = "";
  9. private $m_port = "80";
  10. private $m_user = "";
  11. private $m_pass = "";
  12. private $m_path = "/";
  13. private $m_query = "";
  14. private $m_fp = "";
  15. private $m_error = "";
  16. private $m_httphead = "" ;
  17. private $m_html = "";
  18. /**
  19. * Initialization
  20. */
  21. public function PrivateInit($url){
  22. $urls = "";
  23. $urls = @parse_url($url);
  24. $this->m_url = $url;
  25. if(is_array($urls)) {
  26. $this->m_host = $urls["host"];
  27. if(!empty($urls["scheme"])) $this->m_scheme = $urls["scheme"];
  28. if(!empty($urls["user"])) $this->m_user = $urls["user"];
  29. if(!empty($urls["pass"])) $this->m_pass = $urls["pass"];
  30. if(!empty($urls["port"])) $this->m_port = $urls["port"];
  31. if(!empty($urls["path"])) $this->m_path = $urls["path"];
  32. $this->m_urlpath = $this->m_path;
  33. if(!empty($urls["query"])) {
  34. $this->m_query = $urls["query"];
  35. $this->m_urlpath .= "?".$this->m_query;
  36. }
  37. }
  38. }
  39. /**
  40. *Open the specified URL
  41. */
  42. function OpenUrl($url) {
  43. #重设各参数
  44. $this->m_url = "";
  45. $this->m_urlpath = "";
  46. $this->m_scheme = "http";
  47. $this->m_host = "";
  48. $this->m_port = "80";
  49. $this->m_user = "";
  50. $this->m_pass = "";
  51. $this->m_path = "/";
  52. $this->m_query = "";
  53. $this->m_error = "";
  54. $this->m_httphead = "" ;
  55. $this->m_html = "";
  56. $this->Close();
  57. #初始化系统
  58. $this->PrivateInit($url);
  59. $this->PrivateStartSession();
  60. }
  61. /**
  62. * Get the reason for an operation error
  63. */
  64. public function printError() {
  65. echo "错误信息:".$this->m_error;
  66. echo "具体返回头:
    ";
  67. foreach($this->m_httphead as $k=>$v) {
  68. echo "$k => $v
    rn";
  69. }
  70. }
  71. /**
  72. * Determine whether the response result of the header sent using the Get method is correct
  73. */
  74. public function IsGetOK() {
  75. if( ereg("^2",$this->GetHead("http-state")) ) {
  76. return true;
  77. } else {
  78. $this->m_error .= $this->GetHead("http-state")." - ".$this->GetHead("http-describe")."
    ";
  79. return false;
  80. }
  81. }
  82. /**
  83. * Check whether the returned web page is of text type
  84. */
  85. public function IsText() {
  86. if (ereg("^2",$this->GetHead("http-state")) && eregi("^text",$this->GetHead("content-type"))) {
  87. return true;
  88. } else {
  89. $this->m_error .= "内容为非文本类型
    ";
  90. return false;
  91. }
  92. }
  93. /**
  94. * Determine whether the returned web page is of a specific type
  95. */
  96. public function IsContentType($ctype) {
  97. if (ereg("^2",$this->GetHead("http-state")) && $this->GetHead("content-type") == strtolower($ctype)) {
  98. return true;
  99. } else {
  100. $this->m_error .= "类型不对 ".$this->GetHead("content-type")."
    ";
  101. return false;
  102. }
  103. }
  104. /**
  105. * Download files using HTTP protocol
  106. */
  107. public function SaveToBin($savefilename) {
  108. if (!$this->IsGetOK()) return false;
  109. if (@feof($this->m_fp)) {
  110. $this->m_error = "连接已经关闭!";
  111. return false;
  112. }
  113. $fp = fopen($savefilename,"w") or die("写入文件 $savefilename 失败!");
  114. while (!feof($this->m_fp)) {
  115. @fwrite($fp,fgets($this->m_fp,256));
  116. }
  117. @fclose($this->m_fp);
  118. return true;
  119. }
  120. /**
  121. * Save web content as Text file
  122. */
  123. public function SaveToText($savefilename) {
  124. if ($this->IsText()) {
  125. $this->SaveBinFile($savefilename);
  126. } else {
  127. return "";
  128. }
  129. }
  130. /**
  131. * Use HTTP protocol to obtain the content of a web page
  132. */
  133. public function GetHtml() {
  134. if (!$this->IsText()) return "";
  135. if ($this->m_html!="") return $this->m_html;
  136. if (!$this->m_fp||@feof($this->m_fp)) return "";
  137. while(!feof($this->m_fp)) {
  138. $this->m_html .= fgets($this->m_fp,256);
  139. }
  140. @fclose($this->m_fp);
  141. return $this->m_html;
  142. }
  143. /**
  144. * Start HTTP session
  145. */
  146. public function PrivateStartSession() {
  147. if (!$this->PrivateOpenHost()) {
  148. $this->m_error .= "打开远程主机出错!";
  149. return false;
  150. }
  151. if ($this->GetHead("http-edition")=="HTTP/1.1") {
  152. $httpv = "HTTP/1.1";
  153. } else {
  154. $httpv = "HTTP/1.0";
  155. }
  156. fputs($this->m_fp,"GET ".$this->m_urlpath." $httpvrn");
  157. fputs($this->m_fp,"Host: ".$this->m_host."rn");
  158. fputs($this->m_fp,"Accept: */*rn");
  159. fputs($this->m_fp,"User-Agent: Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.2)rn");
  160. #HTTP1.1协议必须指定文档结束后关闭链接,否则读取文档时无法使用feof判断结束
  161. if ($httpv=="HTTP/1.1") {
  162. fputs($this->m_fp,"Connection: Closernrn");
  163. } else {
  164. fputs($this->m_fp,"rn");
  165. }
  166. $httpstas = fgets($this->m_fp,256);
  167. $httpstas = split(" ",$httpstas);
  168. $this->m_httphead["http-edition"] = trim($httpstas[0]);
  169. $this->m_httphead["http-state"] = trim($httpstas[1]);
  170. $this->m_httphead["http-describe"] = "";
  171. for ($i=2;$i $this->m_httphead["http-describe"] .= " ".trim($httpstas[$i]);
  172. }
  173. while (!feof($this->m_fp)) {
  174. $line = str_replace(""","",trim(fgets($this->m_fp,256)));
  175. if($line == "") break;
  176. if (ereg(":",$line)) {
  177. $lines = split(":",$line);
  178. $this->m_httphead[strtolower(trim($lines[0]))] = trim($lines[1]);
  179. }
  180. }
  181. }
  182. /**
  183. * Get the value of an HTTP header
  184. */
  185. public function GetHead($headname) {
  186. $headname = strtolower($headname);
  187. if (isset($this->m_httphead[$headname])) {
  188. return $this->m_httphead[$headname];
  189. } else {
  190. return "";
  191. }
  192. }
  193. /**
  194. * Open connection
  195. */
  196. public function PrivateOpenHost() {
  197. if ($this->m_host=="") return false;
  198. $this->m_fp = @fsockopen($this->m_host, $this->m_port, &$errno, &$errstr,10);
  199. if (!$this->m_fp){
  200. $this->m_error = $errstr;
  201. return false;
  202. } else {
  203. return true;
  204. }
  205. }
  206. /**
  207. * Close connection
  208. */
  209. public function Close(){
  210. @fclose($this->m_fp);
  211. }
  212. }
  213. #两种使用方法,分别如下:
  214. #打开网页
  215. $httpdown = new HttpDownload();
  216. $httpdown->OpenUrl("http://www.google.com.hk");
  217. echo $httpdown->GetHtml();
  218. $httpdown->Close();
  219. #下载文件
  220. $file = new HttpDownload(); # 实例化类
  221. $file->OpenUrl("http://www.ti.com.cn/cn/lit/an/rust020/rust020.pdf"); # 远程文件地址
  222. $file->SaveToBin("rust020.pdf"); # 保存路径及文件名
  223. $file->Close(); # 释放资源
  224. ?>
复制代码

断点续传, PHP


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)

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,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

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.

See all articles