php curl 发送get post请求


get请求

function _httpGet($url=""){
        
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

post请求

function _httpPost($url="" ,$requestData=array()){
                
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       
        //普通数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($requestData));
        $res = curl_exec($curl);

        //$info = curl_getinfo($ch);
        curl_close($curl);
        return $res;
    }
        // 发送json数据
        $requestData = '{"name":"hello","age":122,"arr":{"arrid":44,"name":"world","test":[333,444,555,66,"xxdfads"]}}';
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length:' . strlen($requestData))); 
        curl_setopt($curl, CURLOPT_POSTFIELDS, $requestData);
        // 服务器端接收json数据  file_get_contents('php://input');

        curl_setopt($ch, CURLOPT_HEADER, 1); //返回response头部信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 时追踪句柄的请求字符串,从 PHP 5.1.3 开始可用。这个很关键,就是允许你查看请求header

        //设置请求头
        $headers = array();
        $header[] = 'User-Agent: iMAG0'; //设置一个你的浏览器agent的header       
        $header[] = 'token:Test'; //设置一个你的浏览器agent的header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        
             
        $info = curl_getinfo($curl);
        foreach ($info as $key => $value) {
            if (is_string($value) || is_int($value)){
                echo $key . ":" . $value ."\r\n";
            }           
        }

声明:小小博客|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - php curl 发送get post请求


Carpe Diem and Do what I like