Receiving a JSON POST [duplicate]

2020-07-18 06:36发布

Possible Duplicate:
How to get body of a POST in php?

I'm receiving a POST that contains a JSON, the problem is when I receive that the $_POST is empty. In order to test when I receive the POST I create a file that contais the $_POST, $_GET and $_REQUEST and they are all empty.

The client that is sending the request is doing something like this:

$itemJson = '{
      "id": 00,
      "value": "ok"
    }';

    $ch = curl_init();

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

To be honest I don't understant how I'm getting this data since there's no parameter set.

Any ideas?

标签: php json post curl
2条回答
冷血范
2楼-- · 2020-07-18 07:07

Try in PHP as below (When request is an application/json, then you will not get data into $_POST)

var_dump(json_decode(file_get_contents("php://input")));
查看更多
冷血范
3楼-- · 2020-07-18 07:16

Try

$request_body = file_get_contents('php://input');
$json = json_decode($request_body);

in your receiving script.

see also: http://docs.php.net/wrappers.php.php

查看更多
登录 后发表回答