search
HomeBackend DevelopmentPHP TutorialPHP download remote file class that supports breakpoint resume download

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.