將curl封裝一個簡單的請求類

<?php

/**
 * Class PHPRequest 進行request請求的類
 * 在請求時,如果要攜帶cookie:
 *      1、可以將cookie存放在文件中,參數$cookie代表文件名,
 *      2、如果cookie是一串字符,可以將其存放在$header中。
 * 一些靜態方法:
 *      1、pregMatch()
 *      2、pregMatchAll()
 *      3、trimHtml()
 * @author john
 */
class PHPRequest
{

    protected $options = array(
        CURLOPT_SSL_VERIFYPEER => FALSE, // 禁止 SSL 驗證
        CURLOPT_SSL_VERIFYHOST => FALSE, // 禁止 SSL 驗證
        CURLINFO_HEADER_OUT => TRUE, //curl_getinfo 結果裏面增加請求的 Headers 信息
        CURLOPT_TIMEOUT => 120, // curl函數執行的最長秒數
        CURLOPT_CONNECTTIMEOUT => 120, // 在嘗試連接時等待的秒數。設置爲0,則無限等待
        CURLOPT_HEADER => FALSE, // 執行結果中是否包含響應的 Headers 頭信息
        CURLOPT_RETURNTRANSFER => TRUE, // curl_exec 執行的結果不自動打印出來
        CURLOPT_NOBODY => FALSE, //輸出 BODY 部分
        CURLOPT_FOLLOWLOCATION => TRUE, //允許重定向
        CURLOPT_MAXREDIRS => 100, //允許重定向次數 最大是100次
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    );

    /**
     * 進行get請求
     * @param $url 請求網址
     * @param string $cookie cookie文件名
     * @param array $header request請求頭
     * @return array
     */
    public function get($url, $cookie = '', $header = array())
    {
        $options = $this->getOptions($cookie, $header);
        return $this->execute($url, $options);
    }


    /**
     * 進行post請求
     * @param $url 請求的網址
     * @param $post 提交的數據
     * @param string $cookie cookie文件
     * @param array $header request請求頭
     * @return array
     */
    public function post($url, $post = null, $cookie = '', $header = array())
    {
        $options = $this->getOptions($cookie, $header, $post);
        return $this->execute($url, $options);
    }


    /**
     * 下載文件
     * @param $url 請求網址
     * @param $file 文件路徑
     * @param string $cookie cookie文件
     * @param array $header request請求頭
     * @param array $post post參數
     * @return array
     */
    public function download($url, $file, $cookie = '', $header = array(), $post = null)
    {
        $options = $this->getOptions($cookie, $header, $post);
        $fp = fopen ($file, 'w+');
        if ($fp === false) {
            return array(
                'code' => '',
                'effective_url' => $file,
                'content' => 'File open fail',
            );
        }

        $options[CURLOPT_FILE] = $fp;
        return $this->execute($url, $options);
        fclose($fp);
    }

    /**
     * 重定向url
     * @param $url
     * @param $max_redirect 最大跳轉次數
     * @return array
     */
    public function redirect($url, $max_redirect){
        $options = $this->options;
        $options[CURLOPT_AUTOREFERER] = TRUE;
        $options[CURLOPT_MAXREDIRS] = $max_redirect;
        return $this->execute($url, $options);
    }

    /**
     * 獲取重定向的全部url
     * @param $url
     * @return array
     */
    public static function getLocation($url){
        $headers = get_headers($url, 1);
        if ($headers && $headers['Location']){
            return $headers['Location'];
        }
        return array();
    }

    /**
     * 通過https://wheregoes.com/retracer.php請求獲取跳轉鏈接
     */
    public function getLocationByApi($url){
        $api = 'https://wheregoes.com/retracer.php';
        $post = array(
            'traceme' => $url,
        );
        $return = $this->post($api, $post);
        preg_match('@<div id="content" class="tracecontent">.*?<div class=".*?_status">@', $return['content'], $matches);
        if(empty($matches[0])){
            return array();
        }else{
            preg_match_all('@>(http[\s\S]+?)<@', $matches[0], $redirect);
            return $redirect;
        }
    }

    /**
     * 獲取某個url的響應頭
     * @param $url
     * @return array
     */
    public function getInfo($url){
        $options = $this->options;
        $options[CURLOPT_HEADER] = TRUE; // 執行結果中是否包含響應的 Headers 頭信息
        $options[CURLOPT_NOBODY] = TRUE; //輸出 BODY 部分
        return $this->execute($url, $options);
    }

    /**
     * 根據正則匹配數據,只匹配一個數據,及正則中只有一個()
     * @param $pattern 正則表達式
     * @param $content
     * @return string
     */
    public static function pregMatch($pattern, $content)
    {
        preg_match($pattern, $content,$matches);
        return empty($matches[1])?"":$matches[1];
    }

    /**
     * 根據正則匹配數據,只匹配一個數據,及正則中只有一個()
     * @param $pattern 正則表達式
     * @param $content
     * @return array
     */
    public static function pregMatchAll($pattern, $content)
    {
        preg_match_all($pattern, $content,$matches);
        return empty($matches[1])?array():$matches[1];
    }

    /**
     * 過濾html中的換行
     * @param $content
     * @return string
     */
    public static function trimHtml($content)
    {
        return preg_replace("/[\t\n\r]+/","",$content);
    }

    protected function getOptions($cookie = '', $header = array(), $post = null)
    {

        $options = $this->options;
        //$cookie不爲空
        if (!empty($cookie)) {
            $options[CURLOPT_COOKIEJAR] = $cookie;
            $options[CURLOPT_COOKIEFILE] = $cookie;
        }
        //$header不爲空
        if (!empty($header)) {
            $options[CURLOPT_HTTPHEADER] = $header;
        }
        //get請求
        if ($post === null) {
            $options[CURLOPT_HTTPGET] = true;
        }else{//post請求
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = $post;
        }
        return $options;
    }

    /**
     * 執行curl請求
     * @param $url
     * @param $options
     * @return array
     */
    protected function execute($url, $options){
        $ch = curl_init($url);

        curl_setopt_array($ch,$options);

        $page = curl_exec($ch);

        //檢查curl是否出錯
        if (curl_errno($ch)) {
            return array(
                'code' => '',
                'effective_url' => $url,
                'content' => array(
                    'info' => curl_error($ch),
                    'no' => curl_errno($ch),
                )
            );
        };

        //句柄信息
        $handleInfo = curl_getinfo($ch);

        curl_close($ch);

        return array(
            'code' => $handleInfo['http_code'],
            'effective_url' => $handleInfo['url'],
            'content' => $page,
        );
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章