天天看點

php curl請求簡單封裝

<?php

class HttpClient {

    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $cookies = array();
    var $referer;
    var $accept = 'text/xml,application/xml,application/xhtml xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    var $accept_encoding = 'gzip';
    var $accept_language = 'en-us';
    var $user_agent = 'Incutio HttpClient v0.9';
    var $debug = false;
    var $content = '';
    var $errormsg;

    function buildRequest() {
        $headers = array();
        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
        $headers[] = "Host: {$this->host}";
        $headers[] = "User-Agent: {$this->user_agent}";
        $headers[] = "Accept: {$this->accept}";

        $headers[] = "Accept-language: {$this->accept_language}";
        if ($this->referer) {
            $headers[] = "Referer: {$this->referer}";
        }

        // If this is a POST, set the content type and length
        if ($this->postdata) {
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            $headers[] = 'Content-Length: ' . strlen($this->postdata);
        }
        $request = implode("\r\n", $headers) . "\r\n\r\n" . $this->postdata;
        return $request;
    }

    function HttpClient($host, $port=80) {
        $this->host = $host;
        $this->port = $port;
    }

    function get($path, $data = false) {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?' . $this->buildQueryString($data);
        }
        return $this->doRequest();
    }

    function post($path, $data) {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = $this->buildQueryString($data);
        return $this->doRequest();
    }

    function buildQueryString($data) {
        $querystring = '';
        if (is_array($data)) {
            ksort($data);
            // Change data in to postable data
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $querystring .= urlencode($key) . '=' . urlencode($val2) . '&';
                    }
                } else {
                    $querystring .= urlencode($key) . '=' . urlencode($val) . '&';
                }
            }
            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
        } else {
            $querystring = $data;
        }
        return $querystring;
    }

    function doRequest() {
        $request = $this->buildRequest();
        if ($this->method == "POST") {
            $url = "http://{$this->host}:{$this->port}" . $this->path;
            return $this->vpost($url);
        } else {
            $url = "http://{$this->host}:{$this->port}" . $this->path;
            return $this->vpost($url);
        }
        return true;
    }

    function vget($url) { // 模拟擷取内容函數
        $curl = curl_init(); // 啟動一個CURL會話

        curl_setopt($curl, CURLOPT_URL, $url); // 要通路的位址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 從證書中檢查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); // 模拟使用者使用的浏覽器
        @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設定Referer
        curl_setopt($curl, CURLOPT_HTTPGET, 1); // 發送一個正常的Post請求
        //curl_setopt ( $curl, CURLOPT_COOKIEFILE, $GLOBALS ['cookie_file'] ); // 讀取上面所儲存的Cookie資訊
        curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 設定逾時限制防止死循環
        curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示傳回的Header區域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 擷取的資訊以檔案流的形式傳回
        $this->content = curl_exec($curl); // 執行操作
        $this->debug($this->content);

        if (curl_errno($curl)) {
            $this->errormsg = 'Errno' . curl_error($curl);
            $this->debug($this->errormsg);
            return false;
        }
        curl_close($curl); // 關閉CURL會話
        return $this->content; // 傳回資料
    }

    function vpost($url) { // 模拟送出資料函數
        $curl = curl_init(); // 啟動一個CURL會話

        curl_setopt($curl, CURLOPT_URL, $url); // 要通路的位址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 從證書中檢查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); // 模拟使用者使用的浏覽器
        @curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設定Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 發送一個正常的Post請求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $this->postdata); // Post送出的資料包
        //curl_setopt($curl, CURLOPT_COOKIEFILE, $GLOBALS ['cookie_file']); // 讀取上面所儲存的Cookie資訊
        curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 設定逾時限制防止死循環
        curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示傳回的Header區域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 擷取的資訊以檔案流的形式傳回
        $this->content = curl_exec($curl); // 執行操作
        $this->debug($this->content.' ,'.$url);

        if (curl_errno($curl)) {
            $this->errormsg = 'Errno' . curl_error($curl);
            $this->debug($this->errormsg.' ,'.$url);
            return false;
        }
        curl_close($curl); // 關鍵CURL會話
        return $this->content; // 傳回資料
    }

    function setUserAgent($string) {
        $this->user_agent = $string;
    }

    function getContent() {
        return $this->content;
    }

    // "Quick" static methods
    public static function quickGet($url) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?' . $bits['query'];
        }
        $client = new HttpClient($host, $port);
        $client->setUserAgent($_SERVER['HTTP_USER_AGENT']);
        if (!$client->get($path)) {
            return false;
        } else {
            return $client->getContent();
        }
    }

    public static function quickPost($url, $data) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        $client->setUserAgent($_SERVER['HTTP_USER_AGENT']);
        if (!$client->post($path, $data)) {
            return false;
        } else {
            return $client->getContent();
        }
    }

    function debug($msg, $object = false) {
        if ($this->debug) {
            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg;
            if ($object) {
                ob_start();
                print_r($object);
                $content = htmlentities(ob_get_contents());
                ob_end_clean();
                print '<pre>' . $content . '</pre>';
            }
            print '</div>';
        }
    }

}

?>