PHP用CURL发送Content-type为application/json的POST请求方法

2020-11-10 09:13:41  [ php ]      留言:0      阅读:4

来源:http://www.oicto.com/php-post-application-json/


PHP用CURL发送Content-type为application/json的POST请求方法

码匠 ·2019年01月1日

PHP发送JSON POST

function json_post($url, $data = NULL) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if(!$data){ return 'data is null'; } if(is_array($data)) { $data = json_encode($data); } curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_HTTPHEADER,array( 'Content-Type: application/json; charset=utf-8', 'Content-Length:' . strlen($data), 'Cache-Control: no-cache', 'Pragma: no-cache' )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($curl); $errorno = curl_errno($curl); if ($errorno) { return $errorno; } curl_close($curl); return $res; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function json_post($url, $data = NULL)
    {
 
        $curl = curl_init();
 
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($data),
                'Cache-Control: no-cache',
                'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;
 
    }

PHP接受JSON POST

$data = json_decode(file_get_contents('php://input'), true);
1
$data = json_decode(file_get_contents('php://input'), true);

来源:http://www.oicto.com/php-post-application-json/


留言:


    更换校验码     

无觅相关文章插件,快速提升流量
分享到:
友荐云推荐 Process: 0.0371s ( Load:0.0003s Init:0.0008s Exec:0.0232s Template:0.0127s ) | DB :14 queries 1 writes | UseMem:3,034 kb