henryspace

记录精彩的程序人生 开始使用

PHP 文件下载类

下载类示例

<?php

namespace App\Libraries;

/**
 * 下载远程文件类支持断点续传
 */
class HttpDownload {
    private $mUrl = "";
    private $mUrlPath = "";
    private $mScheme = "http";
    private $mHost = "";
    private $mPort = "80";
    private $mUser = "";
    private $mPass = "";
    private $mPath = "/";
    private $mQuery = "";
    private $mFp = null;
    private $mError = "";
    private $mHttpHead = [];
    private $mHtml = "";

    /**
     * 初始化
     */
    public function PrivateInit($url){
        $urls = "";
        $urls = @parse_url($url);
        $this->mUrl = $url;
        if(is_array($urls)) {
            $this->mHost = $urls["host"];
            if(!empty($urls["scheme"])) $this->mScheme = $urls["scheme"];
            if(!empty($urls["user"])) $this->mUser = $urls["user"];
            if(!empty($urls["pass"])) $this->mPass = $urls["pass"];
            if(!empty($urls["port"])) $this->mPort = $urls["port"];
            if(!empty($urls["path"])) $this->mPath = $urls["path"];
            $this->mUrlPath = $this->mPath;
            if(!empty($urls["query"])) {
                $this->mQuery = $urls["query"];
                $this->mUrlPath .= "?".$this->mQuery;
            }
        }
    }

    /**
     * 打开指定网址
     */
    function OpenUrl($url) {
        #重设各参数
        $this->mUrl = "";
        $this->mUrlPath = "";
        $this->mScheme = "http";
        $this->mHost = "";
        $this->mPort = "80";
        $this->mUser = "";
        $this->mPass = "";
        $this->mPath = "/";
        $this->mQuery = "";
        $this->mError = "";
        $this->mHttpHead = [] ;
        $this->mHtml = "";
        $this->Close();
        #初始化系统
        $this->PrivateInit($url);
        $this->PrivateStartSession();
    }

    /**
     * 获得某操作错误的原因
     */
    public function printError() {
        echo "错误信息:".$this->mError;
        echo "具体返回头:<br>";
        foreach($this->mHttpHead as $k=>$v) {
            echo "$k => $v <br>\r\n";
        }
    }

    /**
     * 判别用Get方法发送的头的应答结果是否正确
     */
    public function IsGetOK() {
        if( preg_match('#^2#',$this->GetHead("http-state")) ) {
            return true;
        } else {
            $this->mError .= $this->GetHead("http-state")." - ".$this->GetHead("http-describe")."<br>";
            return false;
        }
    }

    /**
     * 看看返回的网页是否是text类型
     */
    public function IsText() {
        if (preg_match('#^2#',$this->GetHead("http-state")) && preg_match('#^text#i',$this->GetHead("content-type"))) {
            return true;
        } else {
            $this->mError .= "内容为非文本类型<br>";
            return false;
        }
    }
    /**
     * 判断返回的网页是否是特定的类型
     */
    public function IsContentType($ctype) {
        if (preg_match('#^2#',$this->GetHead("http-state")) && $this->GetHead("content-type") == strtolower($ctype)) {
            return true;
        } else {
            $this->mError .= "类型不对 ".$this->GetHead("content-type")."<br>";
            return false;
        }
    }

    /**
     * 用 HTTP 协议下载文件
     */
    public function SaveToBin($savefilename) {
        if (!$this->IsGetOK()) return false;
        if (@feof($this->mFp)) {
            $this->mError = "连接已经关闭!";
            return false;
        }
        $fp = fopen($savefilename,"w+") or die("写入文件 $savefilename 失败!");
        while (!feof($this->mFp)) {
            @fwrite($fp,fgets($this->mFp,256));
        }
        @fclose($this->mFp);
        return true;
    }

    /**
     * 保存网页内容为 Text 文件
     */
    public function SaveToText($savefilename) {
        if ($this->IsText()) {
            $this->SaveToBin($savefilename);
        } else {
            return "";
        }
    }

    /**
     * 用 HTTP 协议获得一个网页的内容
     */
    public function GetHtml() {
        if (!$this->IsText()) return "";
        if ($this->mHtml!="") return $this->mHtml;
        if (!$this->mFp||@feof($this->mFp)) return "";
        while(!feof($this->mFp)) {
            $this->mHtml .= fgets($this->mFp,256);
        }
        @fclose($this->mFp);
        return $this->mHtml;
    }

    /**
     * 开始 HTTP 会话
     */
    public function PrivateStartSession() {
        if (!$this->PrivateOpenHost()) {
            $this->mError .= "打开远程主机出错!";
            return false;
        }
        if ($this->GetHead("http-edition")=="HTTP/1.1") {
            $httpv = "HTTP/1.1";
        } else {
            $httpv = "HTTP/1.0";
        }
        fputs($this->mFp,"GET ".$this->mUrlPath." $httpv\r\n");
        fputs($this->mFp,"Host: ".$this->mHost."\r\n");
        fputs($this->mFp,"Accept: */*\r\n");
        fputs($this->mFp,"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->mFp,"Connection: Close\r\n\r\n");
        } else {
            fputs($this->mFp,"\r\n");
        }
        $httpstas = fgets($this->mFp,256);
        $httpstas = explode(' ',$httpstas);
        $this->mHttpHead["http-edition"] = trim($httpstas[0]);
        $this->mHttpHead["http-state"] = trim($httpstas[1]);
        $this->mHttpHead["http-describe"] = "";
        for ($i=2;$i<count($httpstas);$i++) {
            $this->mHttpHead["http-describe"] .= " ".trim($httpstas[$i]);
        }
        while (!feof($this->mFp)) {
            $line = str_replace("\"","",trim(fgets($this->mFp,256)));
            if($line == "") break;
            if (preg_match('#:#',$line)) {
                $lines = explode(':',$line);
                $this->mHttpHead[strtolower(trim($lines[0]))] = trim($lines[1]);
            }
        }
    }

    /**
     * 获得一个Http头的值
     */
    public function GetHead($headname) {
        $headname = strtolower($headname);
        if (isset($this->mHttpHead[$headname])) {
            return $this->mHttpHead[$headname];
        } else {
            return "";
        }
    }

    /**
     * 打开连接
     */
    public function PrivateOpenHost() {
        if ($this->mHost=="") return false;
        $this->mFp = @fsockopen($this->mHost, $this->mPort, $errno, $errstr,10);
        if (!$this->mFp){
            $this->mError = $errstr;
            return false;
        } else {
            return true;
        }
    }

    /**
     * 关闭连接
     */
    public function Close(){
        @fclose($this->mFp);
    }
}

使用示例

#下载文件
$file = new HttpDownload(); # 实例化类
$file->OpenUrl($remoteFileUrl); # 远程文件地址
$file->SaveToBin($localFile); # 保存路径及文件名
$file->Close(); # 释放资源
请成为永远疯狂永远浪漫永远清澈的存在。

评论
留下你的脚步
推荐阅读