【问题标题】:POST empty when curling JSON卷曲 JSON 时 POST 为空
【发布时间】:2012-08-13 00:22:00
【问题描述】:

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

感谢您的宝贵时间

【问题讨论】:

  • 我同意:您没有正确设置 JSON/HTTP 发布数据。看这个链接:stackoverflow.com/questions/8045260/…
  • 我认为你需要引用变量,因为它们是字符串而不是数字
  • @Waygood 确实如此。 JSON 无效。

标签: php json post curl


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 原来应该是'{"firstname":"james"}'
    猜你喜欢
    • 2016-08-12
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2018-09-20
    • 2019-11-02
    • 2013-03-21
    相关资源
    最近更新 更多