curl的get和post的使用方法

php by 黃業(yè)興 at 2020-01-08

get:

public function get_curl(){
    $url = "";
    $parameter = array();
    $ch = curl_init();
    //設(shè)置選項(xiàng),包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $parameter);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//繞過(guò)ssl驗(yàn)證
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT,6);
    //執(zhí)行并獲取HTML文檔內(nèi)容
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    //釋放curl句柄
    curl_close($ch);
    return $result;
}

post:

public function post_curl(){
    $url = "";
    $parameter =  array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //繞過(guò)ssl驗(yàn)證
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    }
    //釋放curl句柄
    curl_close($ch);
    return $result;
}

模擬瀏覽器訪問(wèn)

    public function curl_request($url,$data=array(),$build=false){

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($data)){
            $build && $data = http_build_query($data);
            // RCA:未注意Curl-library Post 1024以上字節(jié)時(shí)的HTTP/1.1特性導(dǎo)致 HessianPHP 傳輸數(shù)據(jù)失敗
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }else{
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            //curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//繞過(guò)ssl驗(yàn)證
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            throw new \Exception($url.':'.curl_error($ch));
            die(curl_error($ch));
        }
        curl_close($ch);
        $encode = mb_detect_encoding($response, array('UTF-8','GB2312','GBK'));
        if($encode != 'UTF-8'){
            $response = $this->to_utf($response);
        }
        return $response;

    }

這里還有個(gè)轉(zhuǎn)換字符的函數(shù)

public function to_utf($str,$ignore=true){
        if($ignore){
            return iconv("GBK","UTF-8//IGNORE",$str);
        }else{
            return iconv("GBK","UTF-8",$str);
        }
    }

請(qǐng)關(guān)注我們微信公眾號(hào):mw748219