php的curl封裝類

以前一直作爬蟲相關的,每次本身去寫一系列curl_setopt()函數太繁瑣,我因而封裝了以下curl請求類。php

<?php
/**
 * @author freephp
 * @date 2015-11-13
 *
 */
class MyCurl {    
    private static  $url = ''; // 訪問的url
    private static $oriUrl = ''; // referer url
    private static $data = array(); // 可能發出的數據 post,put
    private   static $method; // 訪問方式,默認是GET請求
    
    public static function send($url, $data = array(), $method = 'get') {
        if (!$url) exit('url can not be null');
        self::$url = $url;
        self::$method = $method;
        $urlArr = parse_url($url);
        self::$oriUrl = $urlArr['scheme'] .'://'. $urlArr['host'];
        self::$data = $data;
        if ( !in_array(
                self::$method,
                array('get', 'post', 'put', 'delete')
             )
           ) {
                    exit('error request method type!');
             }
        
                $func = self::$method . 'Request';
                return self::$func(self::$url);
    }
    /**
     * 基礎發起curl請求函數
     * @param int $is_post 是不是post請求
     */
    private  function doRequest($is_post = 0) {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, self::$url);//抓取指定網頁
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        // 來源必定要設置成來自本站
        curl_setopt($ch, CURLOPT_REFERER, self::$oriUrl);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果爲字符串且輸出到屏幕上
        if($is_post == 1) curl_setopt($ch, CURLOPT_POST, $is_post);//post提交方式
        if (!empty(self::$data)) {
            self::$data = self::dealPostData(self::$data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data);
        }
        
        $data = curl_exec($ch);//運行curl    
        curl_close($ch);
        return $data;
    }
    /**
     * 發起get請求
     */
    public function getRequest() {
        return self::doRequest(0);
    }
    /**
     * 發起post請求
     */
    public function postRequest() {
        return self::doRequest(1);
    }
    /**
     * 處理髮起非get請求的傳輸數據
     * 
     * @param array $postData
     */
    public function dealPostData($postData) {
        if (!is_array($postData)) exit('post data should be array');
        foreach ($postData as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $postData = substr($o, 0, -1);
        return $postData;
    }
    /**
     * 發起put請求
     */
    public function putRequest($param) {
        return self::doRequest(2);
    }
    
    /**
     * 發起delete請求
     */
    public function deleteRequest($param) {
        return self::doRequest(3);
    }
    
}
/* $curl = new MyCurl('http://www.jumei.com',array(), 'get');
$res = $curl->send(); */
$res = MyCurl::send('http://www.ipip.net/ip.html',array('ip' => '61.142.206.145'),'post');

var_dump($res);die();

考慮到可能會有循環調用的可能和高併發,爲了減小內存堆的沒必要要消耗,我只對客戶端調用提供靜態方法。爲了類的單一職責,MyCurl只作發請求和返回data的做用,對返回數據的處理交給其餘代碼。html

相關文章
相關標籤/搜索