Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving a JSON POST [duplicate]

Tags:

json

post

php

curl

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?

like image 448
fred00 Avatar asked Nov 29 '22 16:11

fred00


2 Answers

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")));
like image 169
GBD Avatar answered Dec 06 '22 04:12

GBD


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

like image 35
VolkerK Avatar answered Dec 06 '22 05:12

VolkerK