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循环输出数据库内容的代码
May 24 PHP
php下intval()和(int)转换使用与区别
Jul 18 PHP
php smarty模版引擎中的缓存应用
Dec 11 PHP
PHPMailer邮件发送的实现代码
May 04 PHP
php的memcache类分享(memcache队列)
Mar 26 PHP
一张表搞清楚php is_null、empty、isset的区别
Jul 07 PHP
PHP面向对象详解(三)
Dec 07 PHP
Zend Framework教程之模型Model基本规则和使用方法
Mar 04 PHP
PHP 数组遍历foreach语法结构及实例
Jun 13 PHP
PHP实现简单的模板引擎功能示例
Sep 02 PHP
php命令行写shell实例详解
Jul 19 PHP
Laravel如何同时连接多个数据库详解
Aug 13 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对mongodb的扩展(初出茅庐)
2012/11/11 PHP
php中cookie的使用方法
2014/03/29 PHP
php项目开发中用到的快速排序算法分析
2016/06/25 PHP
Yii2使用$this-&gt;context获取当前的Module、Controller(控制器)、Action等
2017/03/29 PHP
老生常谈PHP中的数据结构:DS扩展
2017/07/17 PHP
jQuery数据显示插件整合实现代码
2011/10/24 Javascript
javascript获取select的当前值示例代码(兼容IE/Firefox/Opera/Chrome)
2013/12/17 Javascript
js防止DIV布局滚动时闪动的解决方法
2014/10/30 Javascript
跟我学习javascript的call(),apply(),bind()与回调
2015/11/16 Javascript
JQuery ztree带筛选、异步加载实例讲解
2016/02/25 Javascript
JavaScript将DOM事件处理程序封装为event.js 出现的低级错误问题
2016/08/03 Javascript
Javascript中数组去重与拍平的方法示例
2017/02/03 Javascript
JS+CSS+HTML实现“代码雨”类似黑客帝国文字下落效果
2020/03/17 Javascript
elementUI同一页面展示多个Dialog的实现
2020/11/19 Javascript
[02:58]献给西雅图的情书_高清
2014/05/29 DOTA
[02:19]DOTA2上海特级锦标赛 观赛指南 Spectator Guide
2016/02/04 DOTA
python查看FTP是否能连接成功的方法
2015/07/30 Python
python append、extend与insert的区别
2016/10/13 Python
Python 专题三 字符串的基础知识
2017/03/19 Python
PyQt5实现下载进度条效果
2018/04/19 Python
Python 实现还原已撤回的微信消息
2019/06/18 Python
python使用requests.session模拟登录
2019/08/09 Python
详解centos7+django+python3+mysql+阿里云部署项目全流程
2019/11/15 Python
Python 列表推导式需要注意的地方
2020/10/23 Python
使用CSS3在触屏上为按钮实现激活效果
2013/09/27 HTML / CSS
CSS3实现的文本3D效果附图
2014/09/03 HTML / CSS
英国HYPE双肩包官网:英国本土时尚潮牌
2018/09/26 全球购物
哈萨克斯坦移动和数字技术在线商店:SatelOnline.kz
2020/09/04 全球购物
思想政治教育专业个人求职信范文
2013/12/20 职场文书
质监局领导班子对照检查材料思想汇报
2014/09/27 职场文书
冰峪沟导游词
2015/02/09 职场文书
个人廉政承诺书
2015/04/28 职场文书
2015年大学教师工作总结
2015/05/20 职场文书
大学生如何逃脱“毕业季创业队即散伙”魔咒?
2019/08/19 职场文书
Pytorch 统计模型参数量的操作 param.numel()
2021/05/13 Python
Pytorch GPU内存占用很高,但是利用率很低如何解决
2021/06/01 Python