卷曲 JSON 时 POST 为空

问题描述 投票:0回答:2

我正在使用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 数据有什么误解

感谢您的宝贵时间

php json post curl
2个回答
43
投票

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

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

9
投票

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

您需要直接从 POST 正文中读取。

$post = fopen('php://input', 'r');
$data = json_decode(stream_get_contents($post));
fclose($post);
© www.soinside.com 2019 - 2024. All rights reserved.