简体   繁体   中英

POST empty when curling JSON

I'm using curl to send this:

curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{firstname:james}" http://hostname/index.php

I'm trying to display POST like this in index.php

<?php
die(var_dump($_POST)); 
?>

Which outputs

array(0) {
}

I must be misunderstanding something about sending JSON data via POST

Thank you for your time

$_POST is an array that is only populated if you send the POST body in URL encoded format. PHP does not parse JSON by itself automatically and hence does not populate the $_POST array. You need to get the raw POST body and decode the JSON yourself:

$json = file_get_contents('php://input');
$values = json_decode($json, true);

$_POST only works if you are sending encoded form data. You are sending JSON, so PHP cannot parse it into the $_POST array.

You need to read directly from the POST body.

$post = fopen('php://input', r);
$data = json_decode(stream_get_contents($post));
fclose($post);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM