封装php的http请求 get post

get请求

function get_url($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);  //设置访问的url地址
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容
    $result =  curl_exec($ch);
    curl_close ($ch);
    return $result;
}

post请求

    public function curl_post($url, $requestString, $timeout = 5, $json=1) {
        if($url == "" || $requestString == "" || $timeout <= 0){
            return false;
        }
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);
        curl_setopt($con, CURLOPT_POST, true);
        if($json) {
            curl_setopt($con, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($requestString)
            ));
        }
    
        curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名,0不验证
        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);
    
        $curl_return = curl_exec($con);
        if(is_bool($curl_return) && $curl_return == false)
        {
            return json_encode_ex(ReturnError('CURL错误:'.curl_errno($con).'-'.curl_error($con)));
        }
        return $curl_return;
    }

调用post请求试例

$data = ["name"=> "ldg", "data"=>["id"=> ["0"=> ""]]];
$url = 'http://www.summer.kim/admin/userinfo';
$res = $this->curl_post($url, json_encode($data));

你可能感兴趣的:(封装php的http请求 get post)