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 导出数据到淘宝助手CSV的方法分享
Feb 27 PHP
php中定时计划任务的实现原理
Jan 08 PHP
php简单的留言板与回复功能具体实现
Feb 19 PHP
PHP获取中英混合字符串长度的方法
Jun 07 PHP
php利用cookies实现购物车的方法
Dec 10 PHP
php结合正则批量抓取网页中邮箱地址
May 19 PHP
php获取远程文件的内容和大小
Nov 03 PHP
PHP利用imagick生成组合缩略图
Feb 19 PHP
Yii实现的多级联动下拉菜单
Jul 13 PHP
PHP实现表单提交时去除斜杠的方法
Dec 26 PHP
PHP实现动态创建XML文档的方法
Mar 30 PHP
Ajax+PHP实现的分类列表框功能示例
Feb 11 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
PHP4.04简明安装
2006/10/09 PHP
比file_get_contents稳定的curl_get_contents分享
2012/01/11 PHP
php读取本地文件常用函数(fopen与file_get_contents)
2013/09/09 PHP
一个完整的PHP类包含的七种语法说明
2015/06/04 PHP
深入剖析PHP中printf()函数格式化使用
2016/05/23 PHP
PHP实现对二维数组某个键排序的方法
2016/09/14 PHP
TP5框架实现上传多张图片的方法分析
2020/03/29 PHP
jQuery使用手册之三 CSS操作
2007/03/24 Javascript
Jquery实现列表(隔行换色,全选,鼠标滑过当前行)效果实例
2013/06/09 Javascript
IE6 hack for js 集锦
2014/09/23 Javascript
node.js中的fs.closeSync方法使用说明
2014/12/17 Javascript
jquery取消事件冒泡的三种方法(推荐)
2016/05/28 Javascript
详解如何在vue中使用sass
2017/06/21 Javascript
Angular.js中$resource高大上的数据交互详解
2017/07/30 Javascript
基于Vue实例对象的数据选项
2017/08/09 Javascript
200行HTML+JavaScript实现年会抽奖程序
2019/01/22 Javascript
浅谈JavaScript节流和防抖函数
2020/08/25 Javascript
vue实现列表拖拽排序的功能
2020/11/02 Javascript
[04:59]DOTA2-DPC中国联赛 正赛 Ehome vs iG 选手采访
2021/03/11 DOTA
python自动化测试之从命令行运行测试用例with verbosity
2014/09/28 Python
python使用PyGame播放Midi和Mp3文件的方法
2015/04/24 Python
Python常用知识点汇总
2016/05/08 Python
Python实现判断字符串中包含某个字符的判断函数示例
2018/01/08 Python
tensorflow: 查看 tensor详细数值方法
2018/06/13 Python
浅谈numpy生成数组的零值问题
2018/11/12 Python
Python实现根据日期获取当天凌晨时间戳的方法示例
2019/04/09 Python
导入tensorflow:ImportError: libcublas.so.9.0 报错
2020/01/06 Python
基于Python的OCR实现示例
2020/04/03 Python
使用python创建Excel工作簿及工作表过程图解
2020/05/27 Python
深入了解NumPy 高级索引
2020/07/24 Python
如何使用pycharm连接Databricks的步骤详解
2020/09/23 Python
CSS3中颜色线性渐变实战
2015/07/18 HTML / CSS
一年级班主任感言
2014/03/08 职场文书
公司法人授权委托书范本
2014/09/12 职场文书
详解Vue的options
2021/05/15 Vue.js
pytorch训练神经网络爆内存的解决方案
2021/05/22 Python