PHP实现的下载远程文件类定义与用法示例


Posted in PHP onJuly 05, 2017

本文实例讲述了PHP实现的下载远程文件类定义与用法。分享给大家供大家参考,具体如下:

<?php
/**
 * 下载远程文件类支持断点续传
 */
class HttpDownload {
  private $m_url = "";
  private $m_urlpath = "";
  private $m_scheme = "http";
  private $m_host = "";
  private $m_port = "80";
  private $m_user = "";
  private $m_pass = "";
  private $m_path = "/";
  private $m_query = "";
  private $m_fp = "";
  private $m_error = "";
  private $m_httphead = "" ;
  private $m_html = "";
  /**
   * 初始化
   */
  public function PrivateInit($url){
    $urls = "";
    $urls = @parse_url($url);
    $this->m_url = $url;
    if(is_array($urls)) {
      $this->m_host = $urls["host"];
      if(!empty($urls["scheme"])) $this->m_scheme = $urls["scheme"];
      if(!empty($urls["user"])) $this->m_user = $urls["user"];
      if(!empty($urls["pass"])) $this->m_pass = $urls["pass"];
      if(!empty($urls["port"])) $this->m_port = $urls["port"];
      if(!empty($urls["path"])) $this->m_path = $urls["path"];
      $this->m_urlpath = $this->m_path;
      if(!empty($urls["query"])) {
        $this->m_query = $urls["query"];
        $this->m_urlpath .= "?".$this->m_query;
      }
    }
  }
  /**
  * 打开指定网址
  */
  function OpenUrl($url) {
    #重设各参数
    $this->m_url = "";
    $this->m_urlpath = "";
    $this->m_scheme = "http";
    $this->m_host = "";
    $this->m_port = "80";
    $this->m_user = "";
    $this->m_pass = "";
    $this->m_path = "/";
    $this->m_query = "";
    $this->m_error = "";
    $this->m_httphead = "" ;
    $this->m_html = "";
    $this->Close();
    #初始化系统
    $this->PrivateInit($url);
    $this->PrivateStartSession();
  }
  /**
  * 获得某操作错误的原因
  */
  public function printError() {
    echo "错误信息:".$this->m_error;
    echo "具体返回头:<br>";
    foreach($this->m_httphead as $k=>$v) {
      echo "$k => $v <br>\r\n";
    }
  }
  /**
  * 判别用Get方法发送的头的应答结果是否正确
  */
  public function IsGetOK() {
    if( ereg("^2",$this->GetHead("http-state")) ) {
      return true;
    } else {
      $this->m_error .= $this->GetHead("http-state")." - ".$this->GetHead("http-describe")."<br>";
      return false;
    }
  }
  /**
  * 看看返回的网页是否是text类型
  */
  public function IsText() {
    if (ereg("^2",$this->GetHead("http-state")) && eregi("^text",$this->GetHead("content-type"))) {
      return true;
    } else {
      $this->m_error .= "内容为非文本类型<br>";
      return false;
    }
  }
  /**
  * 判断返回的网页是否是特定的类型
  */
  public function IsContentType($ctype) {
    if (ereg("^2",$this->GetHead("http-state")) && $this->GetHead("content-type") == strtolower($ctype)) {
      return true;
    } else {
      $this->m_error .= "类型不对 ".$this->GetHead("content-type")."<br>";
      return false;
    }
  }
  /**
  * 用 HTTP 协议下载文件
  */
  public function SaveToBin($savefilename) {
    if (!$this->IsGetOK()) return false;
    if (@feof($this->m_fp)) {
      $this->m_error = "连接已经关闭!";
      return false;
    }
    $fp = fopen($savefilename,"w") or die("写入文件 $savefilename 失败!");
    while (!feof($this->m_fp)) {
      @fwrite($fp,fgets($this->m_fp,256));
    }
    @fclose($this->m_fp);
    return true;
  }
  /**
  * 保存网页内容为 Text 文件
  */
  public function SaveToText($savefilename) {
    if ($this->IsText()) {
      $this->SaveBinFile($savefilename);
    } else {
      return "";
    }
  }
  /**
  * 用 HTTP 协议获得一个网页的内容
  */
  public function GetHtml() {
    if (!$this->IsText()) return "";
    if ($this->m_html!="") return $this->m_html;
    if (!$this->m_fp||@feof($this->m_fp)) return "";
    while(!feof($this->m_fp)) {
      $this->m_html .= fgets($this->m_fp,256);
    }
    @fclose($this->m_fp);
    return $this->m_html;
  }
  /**
  * 开始 HTTP 会话
  */
  public function PrivateStartSession() {
    if (!$this->PrivateOpenHost()) {
      $this->m_error .= "打开远程主机出错!";
      return false;
    }
    if ($this->GetHead("http-edition")=="HTTP/1.1") {
      $httpv = "HTTP/1.1";
    } else {
      $httpv = "HTTP/1.0";
    }
    fputs($this->m_fp,"GET ".$this->m_urlpath." $httpv\r\n");
    fputs($this->m_fp,"Host: ".$this->m_host."\r\n");
    fputs($this->m_fp,"Accept: */*\r\n");
    fputs($this->m_fp,"User-Agent: Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.2)\r\n");
    #HTTP1.1协议必须指定文档结束后关闭链接,否则读取文档时无法使用feof判断结束
    if ($httpv=="HTTP/1.1") {
      fputs($this->m_fp,"Connection: Close\r\n\r\n");
    } else {
      fputs($this->m_fp,"\r\n");
    }
    $httpstas = fgets($this->m_fp,256);
    $httpstas = split(" ",$httpstas);
    $this->m_httphead["http-edition"] = trim($httpstas[0]);
    $this->m_httphead["http-state"] = trim($httpstas[1]);
    $this->m_httphead["http-describe"] = "";
    for ($i=2;$i<count($httpstas);$i++) {
      $this->m_httphead["http-describe"] .= " ".trim($httpstas[$i]);
    }
    while (!feof($this->m_fp)) {
      $line = str_replace("\"","",trim(fgets($this->m_fp,256)));
      if($line == "") break;
      if (ereg(":",$line)) {
        $lines = split(":",$line);
        $this->m_httphead[strtolower(trim($lines[0]))] = trim($lines[1]);
      }
    }
  }
  /**
  * 获得一个Http头的值
  */
  public function GetHead($headname) {
    $headname = strtolower($headname);
    if (isset($this->m_httphead[$headname])) {
      return $this->m_httphead[$headname];
    } else {
      return "";
    }
  }
  /**
  * 打开连接
  */
  public function PrivateOpenHost() {
    if ($this->m_host=="") return false;
    $this->m_fp = @fsockopen($this->m_host, $this->m_port, &$errno, &$errstr,10);
    if (!$this->m_fp){
      $this->m_error = $errstr;
      return false;
    } else {
      return true;
    }
  }
  /**
  * 关闭连接
  */
  public function Close(){
    @fclose($this->m_fp);
  }
}
#两种使用方法,分别如下:
#打开网页
$httpdown = new HttpDownload();
$httpdown->OpenUrl("http://www.google.com.hk");
echo $httpdown->GetHtml();
$httpdown->Close();
#下载文件
$file = new HttpDownload(); # 实例化类
$file->OpenUrl("http://www.ti.com.cn/cn/lit/an/rust020/rust020.pdf"); # 远程文件地址
$file->SaveToBin("rust020.pdf"); # 保存路径及文件名
$file->Close(); # 释放资源
?>

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
用PHP实现文件上传二法
Oct 09 PHP
php &amp;&amp; 逻辑与运算符使用说明
Mar 04 PHP
Wordpress 相册插件 NextGEN-Gallery 添加目录将中文转为拼音的解决办法
Dec 29 PHP
PHP curl模拟浏览器采集阿里巴巴的实现代码
Apr 20 PHP
php实现执行某一操作时弹出确认、取消对话框
Dec 30 PHP
PHP实现取得HTTP请求的原文
Aug 18 PHP
PHP跨平台获取服务器IP地址自定义函数分享
Dec 29 PHP
简单介绍win7下搭建apache+php+mysql开发环境
Aug 06 PHP
Yii数据模型中rules类验证器用法分析
Jul 15 PHP
Kindeditor编辑器添加图片上传水印功能(php代码)
Aug 03 PHP
PHP两个n位的二进制整数相加问题的解决
Aug 26 PHP
关于laravel框架中的常用目录路径函数
Oct 23 PHP
详解PHP使用Redis存储session时的一个Warning定位
Jul 05 #PHP
php如何修改SESSION的生存存储时间的实例代码
Jul 05 #PHP
PHP实现根据密码长度显示安全条
Jul 04 #PHP
PHP截取发动短信内容的方法
Jul 04 #PHP
phpcms配置列表页以及获得文章发布时间
Jul 04 #PHP
一个非常实用的php文件上传类
Jul 04 #PHP
php基于数组函数实现关联表的编辑操作示例
Jul 04 #PHP
You might like
深入PHP数据缓存的使用说明
2013/05/10 PHP
JavaScript入门教程(7) History历史对象
2009/01/31 Javascript
关于Ext中form移除textfield方法:hide(),setVisible(false),remove()
2010/12/02 Javascript
AngularJS入门知识之MVW类框架的编程思想探讨
2014/12/08 Javascript
AngularJS基础学习笔记之指令
2015/05/10 Javascript
浅谈在js传递参数中含加号(+)的处理方式
2016/10/11 Javascript
webpack学习笔记之优化缓存、合并、懒加载
2017/08/24 Javascript
vue项目中使用axios上传图片等文件操作
2017/11/02 Javascript
async/await地狱该如何避免详解
2018/05/10 Javascript
js数组去重的N种方法(小结)
2018/06/07 Javascript
详解mpvue实现对苹果X安全区域的适配
2019/07/31 Javascript
p5.js临摹动态图形实现方法详解
2019/10/23 Javascript
js中addEventListener()与removeEventListener()用法案例分析
2020/03/02 Javascript
[03:36]DOTA2完美大师赛coL战队趣味视频——我演你猜
2017/11/23 DOTA
python杀死一个线程的方法
2015/09/06 Python
Flask框架Flask-Login用法分析
2018/07/23 Python
python发送多人邮件没有展示收件人问题的解决方法
2019/06/21 Python
Java文件与类动手动脑实例详解
2019/11/10 Python
python pygame实现球球大作战
2019/11/25 Python
Python3 hashlib密码散列算法原理详解
2020/03/30 Python
Python爬取阿拉丁统计信息过程图解
2020/05/12 Python
详解python百行有效代码实现汉诺塔小游戏(简约版)
2020/10/30 Python
HTML5 Canvas中使用路径描画二阶、三阶贝塞尔曲线
2015/01/01 HTML / CSS
佳能加拿大网上商店:Canon eStore Canada
2018/04/04 全球购物
StubHub澳大利亚:购买或出售您的门票
2019/08/01 全球购物
PHP高级工程师面试问题推荐
2013/01/18 面试题
法务专员岗位职责
2014/01/02 职场文书
经典安踏广告词
2014/03/21 职场文书
中学生教师节演讲稿
2014/09/03 职场文书
党员创先争优心得体会
2014/09/11 职场文书
2014医学院领导班子对照检查材料思想汇报
2014/09/19 职场文书
2015年学校党支部工作总结
2015/04/01 职场文书
2015年医院后勤工作总结
2015/05/20 职场文书
六年级作文之关于梦
2019/10/22 职场文书
python库Tsmoothie模块数据平滑化异常点抓取
2022/06/10 Python
HTML5中的DOCUMENT.VISIBILITYSTATE属性详解
2023/05/07 HTML / CSS