卷曲 JSON 时 POST 为空


POST empty when curling JSON

我正在使用curl发送这个:

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

我正在尝试在索引中显示这样的 POST.php

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

哪些输出

array(0) {
}

我一定误解了通过 POST 发送 JSON 数据

谢谢你的时间

> $_POST 是一个数组,仅当您以 URL 编码格式发送 POST 正文时才会填充该数组。PHP 不会自动解析 JSON,因此不会填充 $_POST 数组。您需要获取原始 POST 正文并自行解码 JSON:

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

$_POST仅在发送编码表单数据时才有效。 您正在发送 JSON,因此 PHP 无法将其解析为 $_POST 数组。

您需要直接从开机自检正文中读取。

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