【PHP】curl请求

版权声明:咔咔 来自https://blog.csdn.net/fangkang7 https://blog.csdn.net/fangkang7/article/details/86361084

author:咔咔

wechat:fangkangfk

没有data数据为get请求,有data数据未post请求

public function request($url, $data=array()){

        $ch = curl_init();//初始化
        //curl_setopt();//设置

        //设置
        curl_setopt($ch,CURLOPT_URL,$url);   //需要获取的 URL 地址
        curl_setopt($ch,CURLOPT_HEADER,0);          //启用时会将头文件的信息作为数据流输出, 此处禁止输出头信息
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  //获取的信息以字符串返回,而不是直接输出
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30); //连接超时时间
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

        //避免https 的ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


        if($data){
            curl_setopt($ch, CURLOPT_POST, 1);          //post请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post参数
        }


        //执行
        $data = curl_exec($ch);//执行   不输出  内容返回给它
        //判断是否请求成功

        if(curl_errno($ch)){//错误码
            echo 'curl error: '.curl_error($ch);//错误信息
        }

        $response = curl_getinfo($ch);

        switch($response['http_code']){
            case 200:
                return $data;
                break;
            default:
                exit('程序异常');
        }

        curl_close($ch);//关闭

    }

猜你喜欢

转载自blog.csdn.net/fangkang7/article/details/86361084