php curl

curl post json格式数据

    function curlPost($url, $data = array())
    {
        $data = array("name" => "TEST", "age" => "20");
        $data_string = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

数据接受方:(使用$_POST获取不到)

$req = file_get_contents("php://input"); // string
$arr = json_decode($req,true);
print_r($arr);

$arr = $_POST;// arr 为空数组

post application/x-www-form-urlencoded数据

 function httpPost()
    {
        $url = '';
        $data = array();
        
        $headers = array();
        $headers[] = "headdata1: 123";
        $headers[] = "headdata2: 456";
        $headers[] = "Content-Type: application/x-www-form-urlencoded"; // 可不填

        $post_data = $data;

        $post_data = http_build_query($post_data);

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

数据接受方:(使用$_POST获取不到)

$arr = $_POST;
print_r($arr);

curl GET:

function httpGET($url)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, true);
        //设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //执行命令
        $ret = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return $ret;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值