php curl封裝類

來源:互聯網
上載者:User
一個php curl封裝的類,減少代碼量,簡化採集工作。這個類也是我工作的最常用的類之一。這裡分享給大家。配合上phpquery,十分好用。

 '', // 請求的URL        CURLOPT_RETURNTRANSFER => 1, // 設定有返回資訊,以流的形式返回,非不是直接輸出        CURLOPT_HTTPGET => 1, // 設定為GET請求。        // 定義預設的回呼函數,這樣exec()將在成功後返回1        CURLOPT_CONNECTTIMEOUT => 30, // 設定預設連結逾時間為30秒        CURLOPT_TIMEOUT=>30,//設定下載時間最多30秒。        // 自動跟蹤重新導向。        CURLOPT_FOLLOWLOCATION => true,        // 設定用戶端支援gzip壓縮,預設不開啟,用於節省流量。        CURLOPT_ENCODING => 'gzip',        // 設定預設header頭        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0'    );        public $opt;        public $cookieFile = false; // 儲存的COOKIE檔案    /**     * http請求響應的緩衝,預設緩衝在數組中,最大為512個     * @var array     */    public $cache = array();    public function __construct ()    {        // 完成CH的初始化        $this->ch = curl_init();        if (! $this->ch)            die('當前環境不支援CURL');        $this->opt=$this->defaultOpt;    }    // 執行HTTP請求,並得到返回資料    // 返回指定匹配的串,如果匹配失敗將返回全部文檔    public function exec ($opt)    {        //如查參數只是一個串,就認為是一個url        if(!is_array($opt))        {            $url=$opt;            $opt=array();            $opt['url']=$url;        }        // 如果存在緩衝,則返回緩衝的字串。        $key = md5($opt['url'] . $opt['post'] . $opt['match']. $opt['return']);        if (($str = $this->getCache($key)) != false)            return $str;            // 每次執行前,清空當前str,每次請求,傳回值可能不一樣        $this->str = '';        // 參數設定失敗和執行行失敗都將返回 fasle;        if (! $this->setOptions($opt))            return false;        $flag = curl_exec($this->ch);        $this->setCache($key, $this->str ? $this->str : $flag);                //執行完成後,基於長駐記憶體和考慮,上一次串連的選項可以對下一次靠成影響        $this->opt=$this->defaultOpt;                if ($this->str == '') // 表示沒有執行回呼函數            return $flag;        else            return $this->str;    }        /**     * 簡單封裝的file_get_contents函數     * 只是使用的緩衝而已。     */     public function getContent ($url)    {        $key = md5($url);        if (($str = $this->getCache($key)) != false)            return $str;        $str = file_get_contents($url);        $this->setCache($key, $str);        return $str;    }    // 設定CURL屬性    public function setOptions ($opt)    {        foreach ($opt as $key => $value) {            // 以下值為可以設定的值。如果沒有,將使用預設值;            switch ($key) {                case 'url': // 設定當前請求的URL                    $this->opt[CURLOPT_URL] = $value;                    break;                case 'str': // 設定資訊返方式,預設為1                    $this->opt[CURLOPT_RETURNTRANSFER] = $value;                    break; // 預設值也為1                case 'method': // 設定請求方式,預設為POST                    if ($value == 'get')                        $this->opt[CURLOPT_HTTPGET] = 1; // 設為GET請求                    elseif ($value == 'put')                        $this->opt[CURLOPT_PUT] = 1; // ftp檔案上傳                    else                        $this->opt[CURLOPT_POST] = 1;                    break;                case 'post': // 設定POST請求主體,數組形式,如果上傳檔案,檔案名稱前加@                    $this->opt[CURLOPT_POSTFIELDS] = $value;                    break;                case 'header': // 設定HEADER要求標頭;預設不使用,數組形式                    $this->opt[CURLOPT_HTTPHEADER] = $value;                    break;                case 'referer': // 設定REFERER資訊,預設為空白                    $this->opt[CURLOPT_REFERER] = $value;                    break;                case 'auth': // 設定要請求的使用者密碼[username]:[password]                    $this->opt[CURLOPT_USERPWD] = $value;                    break;                case 'connect_time': // 發起連結前的等待時間                    $this->opt[CURLOPT_CONNECTTIMEOUT] = $value;                    break;                case 'load_time'://檔案下載最長時間。                    $this->opt[CURLOPT_TIMEOUT]=$value;                    break;                case 'callback': // 定義回呼函數                    $this->opt[CURLOPT_WRITEFUNCTION] = $value;                    break;                case 'match': // 尋找指定段的Regex                    $this->opt[CURLOPT_WRITEFUNCTION] = array(                        'self',                        'callback'                    );                    $this->match = $value;                case 'proxy':                    $this->opt[CURLOPT_PROXY] = $value;                    break;                case 'file': // 用FTP上傳的檔案名稱柄                    $this->opt[CURLOPT_VERBOSE] = 1;                    $this->opt[CURLOPT_INFILE] = $value; // 上傳控制代碼                    $this->opt[CURLOPT_NOPROGRESS] = false;                    $this->opt[CURLOPT_FTP_USE_EPRT] = true;                    $this->opt[CURLOPT_FTP_USE_EPSV] = true;                    break;                case 'cookie_file': // 設定cookie檔案。                     $this->cookieFile =APP_PATH . '/runtime/cookie.txt';                     // 發送COOKIE                     $this->opt[CURLOPT_COOKIEFILE] = $this->cookieFile;                     // 設定cookie                    $this->opt[CURLOPT_COOKIEJAR] = $this->cookieFile;                    break;                case 'cookie'://設定訪問cookie為一個字串                    $this->opt[CURLOPT_COOKIE]=$value;                    break;                case 'return': // 設定返回的類型                    if ($value == 'head') // 表示只得到header頭                    {                        $this->opt[CURLOPT_NOBODY] = 1;                        $this->opt[CURLOPT_HEADER] = 1;                    }                     elseif ($value == 'body') {}// 預設值,只返回body體                    elseif ($value == 'all')                        $this->opt[CURLOPT_HEADER] = 1;                    break;                case 'location'://是不是跟蹤重新導向                    $this->opt[CURLOPT_FOLLOWLOCATION]=$value;                    break;                case 'client_type'://設定用戶端類型                    $this->setClientType($value);                    break;                case 'client_ip'://設定用戶端IP地址,只是在header頭,不是真實偽造                    $this->opt[CURLOPT_HTTPHEADER][]='X-FORWARDED-FOR: '.$value;                    $this->opt[CURLOPT_HTTPHEADER][]='CLIENT-IP: '.$value;                    break;            }        }        // 設定當前連結選項,選項設定失敗返回false;        return curl_setopt_array($this->ch, $this->opt);    }    // 回呼函數,返回指定Regex的HTML段    public function callback ($ch, $str)    {        $this->str .= $str;        preg_match($this->match, $this->str, $match);        if (! empty($match))         {            // 存在一個子模式,則返回這個子模式            if (isset($match[1]))                $this->str = $match[1];            else                $this->str = $match[0];            return false; // 插斷要求        }        return strlen($str);    }    /**     * 得到當前請求的錯誤資訊     * @param int $type     *  0表示得到錯誤編碼,1表示得到錯誤資訊,2表示得到所有資訊     * @return mixed     */    public function getError ($type = 11)    {        switch ($type) {            case 0:                $info = curl_errno($this->ch);                break;            case 1:                $info = curl_error($this->ch);                break;            default:                $info = curl_getinfo($this->ch);        }        return $info;    }    /**     * 清除緩衝。     */    public function __destruct ()    {        curl_close($this->ch);        $this->cache = array();    }    /**     * 設定緩衝,以減少http請求數量。     * 大量採集中,你應改使用重寫此方法。     * 預設將使用記憶體緩衝     * 如果緩衝數組超過512個,清空數組緩衝。     * @param string $key                 * @param string $str                 * @return string boolean     */    public function setCache ($key, $str)    {        if(count($this->cache)>512)            $this->cache=array();        $this->cache[$key] = $str;                //如果引入的phpquery對象        if(class_exists('\\phpQuery') && count(\phpQuery::$documents)>512)            \phpQuery::$documents=array();    }    /**     * 得到快取資料     *      * @param string $key                 * @return string boolean     */    public function getCache ($key)    {        if ($this->cache[$key])            return $this->cache[$key];        else            return false;    }    /**     * 調用遠程http介面,返回一個數組     * 當前只支援get請求     * @param string $url     * @param array $query get方式查詢參數     * 其中兩個參數為自訂參數     * _method:為請求的類型     * _type:為返回的資料類型,支援xml,json.     * 這兩個參數不做查詢字串     * @param array $type 返回的格式類型     */    public function getArray($url,$query=array())    {        $method=($query['_method']=='post')?'post':'get';        $type = ($query['_type']=='xml')?'xml':'json';    if($query['_method'])        unset($query['_method']);    if($query['_type'])        unset($query['_type']);    if($method=='get')    {        if($query)            $nowUrl=$url.'?'.http_build_query($query);        else             $nowUrl=$url;        $str=$this->exec(array(        'url'=>$nowUrl,        'method'=>'get',        ));    }    else         $str=$this->exec(array(            'url'=>$url,            'method'=>'post',            'post'=>$query        ));    if(!$str)        return false;$arr=$this->toArray($str,$type);if(!$arr || !is_array($arr))    return false;return $arr;            }    /**     * 將一個{}格式的javasrcipt對象轉變成一個php數組     * 以避免過多的使用Regex。     * 目前支援一維數組;     * 如果js對像裡面還有一個對象。可能會有問題。     * 通常情況下,你應該在頁面中只匹配一個JS對象。     * @param string $str     * @return array|bool     */    public function jsArray($str)    {        $return=array();    $str=str_replace(array(        '"',        "'",        '{',        '}'    ), '', $str);    $arr=explode(',', $str);    foreach($arr as $row)    {    $tmpArr=explode(':', $row);    $return[trim($tmpArr[0])]=trim($tmpArr[1]);    }    return $return;    }    /**     * 使用phpquery來進行html頁面採集     * @param unknown $str 字串     * @param string $query 選取器運算式     * @return \phpQuery     */    public function getDom($str,$query='')    {        require_once APP_PATH.'/iphp/extension/phpQuery/phpQuery.php';        $domObject=\phpQuery::newDocument($str);        if($query=='')            return $domObject;        return pq($query);    }        /**     * 將字串轉變成一個數組;     * @param string $str 字串     * @param string $type 類型。     * @return array|bool     */    public function toArray($str,$type="json")    {        if($type=='xml')        {            $doc=simplexml_load_string($str);            $xml=App::getApp()->getXml();            return $xml->getTreeArray($doc);        }        elseif($type=='json')            return json_decode($str,true);        elseif($type=='query')        {            $parse=parse_url($str);            parse_str($parse['query'],$params);            return $params;        }        elseif($type=='pathinfo')        {                    }    }        /**     * 根據type類型預設瀏覽器用戶端     * @param type $type     * iphone 表示iphone用戶端,     * pc 表示電腦客戶用戶端,     * android 表示安卓用戶端      */    public function setClientType($type)    {    $userAgent=array(        'pc'=>'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0',        'iphone'=>'Mozilla/5.0 (iPad; U; CPU OS 3_2_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B500 Safari/531.21.10',        'android'=>'Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'    );    if(array_key_exists($type,$userAgent))        $this->opt[CURLOPT_USERAGENT]=$userAgent[$type];    }        //關閉當前資源串連    public function close()    {        curl_close($this->ch);    }}

使用樣本:

 array ('sdtv','98/0','山東衛視' ),1 => array ('qlpd','98/1','齊魯頻道' ),2 => array ('ggpd','98/2','公用頻道' ),3 => array ('typd','98/3','體育頻道' ),4 => array ('shpd','99/2','生活頻道' ),5 => array ('zypd','100/0','綜藝頻道' ),6 => array ('nkpd','99/0','農科頻道' ),7 => array ('yspd','99/3','影視頻道' ),8 => array ('sepd','99/1','少兒頻道' ),9 => array ('gjpd','100/1','國際頻道' )/*,10 => array ('dspd','107/6','讀書頻道' ) */);foreach ( $lists as $item ) {$vid = $item [0] . ',' . $item [1] . ',' . $item [2];$channel_name = $item [2];$link = $this->getAll ( $vid );$this->info [] = array ('channel_name' => $channel_name,'channel_link' => $link );}return $this->info;}public function one($vid, $format) {$arr2 = explode ( ',', $vid );if ($format != 1) {return false;}$url = "http://huodong.iqilu.com/active/video/clientnew/public_s/?c=";$str = $this->curl->exec ( array ('url' => $url . $arr2 [0],'header' => array ('Host: huodong.iqilu.com',//'User-Agent: Android',//"Referer: http://v.iqilu.com/live/{$arr2[0]}/",'User-Agent: Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; Coolpad 8675 Build/KOT49H) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/9.9.7.500 U3/0.8.0 Mobile Safari/534.30',),'referer' => "http://m.iqilu.com/vms/live/{$arr2[0]}/",'client_type' => "android" ) );$arr = explode('|', $str);$vid = "http://m3u8.iqilu.com/live/$arr2[1].m3u8?st=".$arr[16].$arr[17]."&e=".$arr[19].$arr[20];//&e={$arr[17]};return $vid;}}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.