封装的一个curl方法:

<?php

$a=new CURL();
$a->url="https://baidu.com";
echo $a->run();


class CURL{
    //URL地址
    public $url='';
    //提交方式
    public $method='GET';
    //提交数据
    public $data;
    //提交协议头
    public $head=array();
    //cookie文件路径
    public $cookies='';
    //提交的header头
    public $header_info='';
    //返回状态码
    public $http_code=0;
    //请求错误信息
    public $http_error=false;
    //开始请求
    public function run($func=null){
        if(!$this->url){
            return "error:url";
        }
        $heads[]='User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31';
        if($this->head){
            foreach ($this->head as $v) {
                $heads[] = $v;
            }
        }
        $heads[] = 'Accept: text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $heads[] = 'Accept-Encoding: gzip, deflate, Brotli';
        if(is_array($this->data)){
            $this->data=http_build_query($this->data);
        }else{
            if(json_decode($this->data,true)){
                $heads[] ="Content-Type: application/json; charset=utf-8";
                $heads[] ="Content-Length: " . strlen($this->data);
            }
        }
        $curl_info=array(
            CURLOPT_TIMEOUT=>0, // 最大执行时间
            CURLOPT_AUTOREFERER=> true, // 自动设置Referer
            CURLOPT_URL=>$this->url, // 要访问的地址
            CURLOPT_HEADER=>false,// 设置是否显示返回头信息  1返回 0不返回  调试开启
            CURLOPT_NOBODY=>false, //不想在输出中包含body部分,设置这个选项为一个非零值
            CURLOPT_RETURNTRANSFER=>true,//获取的信息以文件流的形式返回
            CURLOPT_BINARYTRANSFER=>true, //在启用CURLOPT_RETURNTRANSFER的时候,返回原生的(Raw)输出。
            CURLOPT_SSL_VERIFYPEER=>FALSE,//https 不进行ssl验证
            CURLOPT_SSL_VERIFYHOST=>FALSE,
            CURLOPT_HTTPHEADER=>$heads,//设置头信息
            CURLOPT_CUSTOMREQUEST=>$this->method, //设置请求方式
            CURLINFO_HEADER_OUT=>true,//TRUE 时允许你查看请求header
            CURLOPT_ACCEPT_ENCODING=>"gzip,deflate,Brotli",
            CURLOPT_WRITEFUNCTION=> $func,
            CURLOPT_COOKIEFILE=> $this->cookies,//设置cookies文件
            CURLOPT_COOKIEJAR=> $this->cookies,//设置cookies文件
            CURLOPT_POSTFIELDS=>$this->data
         );
        if(!$this->cookies){
            unset($curl_info[CURLOPT_COOKIEFILE]);
            unset($curl_info[CURLOPT_COOKIEJAR]);
        }
        if($func==null){
            unset($curl_info[CURLOPT_WRITEFUNCTION]);
        }
        //发送http请求
        $ch= curl_init();
        curl_setopt_array($ch, $curl_info);
        //发送请求获取返回响应
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            $this->http_error=curl_error($ch);
            $result = false;
        }else{
            $this->header_info=curl_getinfo($ch, CURLINFO_HEADER_OUT);
            $this->http_code=curl_getinfo($ch,CURLINFO_HTTP_CODE);
        }
        curl_close($ch);
        return $result;
    }
}
如果觉得我的文章对你有用,请随意赞赏