卷曲JSON时POST为空

时间:2012-08-16 15:37:00

标签: php json post curl

我正在使用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数据的事情

感谢您的时间

2 个答案:

答案 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);