You send the data as raw JSON in the body, it will not populate the $_POST variable.
You need to do one of two things:
- You can change the content type to the one that fills the
$_POST array - You can read the original body data.
I would recommend option two if you have control over both ends of the connection, as it will keep the request body size to a minimum and maintain bandwidth over time. (Editing: I did not particularly emphasize here that the amount of bandwidth that it will save is negligible, only a few bytes per request, this will only be an urgent problem, this is a very high traffic environment. However, I still recommend option two, because what is the cleanest way)
In your test_curl file do the following:
$fp = fopen('php://input', 'r'); $rawData = stream_get_contents($fp); $postedJson = json_decode($rawData); var_dump($postedJson);
If you want to populate the $_POST variable, you will need to change the way data is sent to the server:
$data = array ( 'name' => 'Hagrid', 'age' => '36' ); $bodyData = array ( 'json' => json_encode($data) ); $bodyStr = http_build_query($bodyData); $url = 'http://localhost/project/test_curl'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded', 'Content-Length: '.strlen($bodyStr) )); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr); $result = curl_exec($ch);
Raw, unencoded JSON will now be available in $_POST['json'] .
source share