我正在使用curl发送此信息:
curl -i -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{firstname:james}" http://hostname/index.php
我正在尝试在index.php中显示这样的POST
<?php
die(var_dump($_POST));
?>
哪个输出
array(0) {
}
我必须误解一些关于通过POST发送JSON数据的事情
感谢您的时间
答案 0 :(得分:28)
$_POST
是一个数组,仅当您以URL编码格式发送POST正文时才会填充。 PHP不会自动解析JSON,因此不会填充$_POST
数组。您需要获取原始POST正文并自行解码JSON:
$json = file_get_contents('php://input');
$values = json_decode($json, true);
答案 1 :(得分:6)
$_POST
仅在您发送编码的表单数据时才有效。您正在发送JSON,因此PHP无法将其解析为$_POST
数组。
您需要直接从POST正文中阅读。
$post = fopen('php://input', r);
$data = json_decode(stream_get_contents($post));
fclose($post);