【问题标题】:Cant post data in body in PHP无法在 PHP 中的正文中发布数据
【发布时间】:2018-02-13 00:35:32
【问题描述】:

我正在尝试发布以下 json 数据

{"name":"somename","email":"somemail","password":"abcdef"}

在我的 api 中,

<?php


require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['name']) && isset($_POST['email']) && 
isset($_POST['password'])) {

// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
    // user already existed
    $response["error"] = TRUE;
    $response["error_msg"] = "User already existed with " . $email;
    echo json_encode($response);
} else {
    // create a new user
    $user = $db->storeUser($name, $email, $password);
    if ($user) {
        // user stored successfully
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        echo json_encode($response);
    } else {
        // user failed to store
        $response["error"] = TRUE;
        $response["error_msg"] = "Unknown error occurred in registration!";
        echo json_encode($response);
    }
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is 
missing!";
echo json_encode($response);
}
?>

我的问题是if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) 总是假的,而消息Required parameters (name, email or password) is missing! is shown

在 wampserver 日志中,错误显示为

不推荐使用 PHP:自动填充 $HTTP_RAW_POST_DATA 是 已弃用,并将在未来的版本中删除。为了避免这种情况 警告在 php.ini 中将“always_populate_raw_post_data”设置为“-1”并使用 php://input 流。在第 0 行的未知中

【问题讨论】:

  • "password","abcdef" 应该像其他人一样是冒号,n'est-ce pas? 编辑:此评论根据原帖stackoverflow.com/revisions/46042691/1
  • 是的,这是一个类型错误
  • 这个的html/form在哪里?
  • 我使用邮递员发布数据
  • 我现在只能问:你用的是什么版本的php?如果您使用的是 7,则不能再使用/依赖它php.net/manual/en/reserved.variables.httprawpostdata.php 并且还声明:“通常,应使用 php://input 而不是 $HTTP_RAW_POST_DATA。”

标签: php mysql


【解决方案1】:

如果以 json 格式发送 post 数据,在 api 中您必须将输入数据解码为数组

$data = json_decode($_POST)

然后继续条件

if (isset($data['name'], $data['email'], $data['password']) {

【讨论】:

    【解决方案2】:

    注意:这是一个社区 wiki 答案。

    根据$HTTP_RAW_POST_DATA上的手册

    http://php.net/manual/en/reserved.variables.httprawpostdata.php

    “一般来说,应该使用 php://input 而不是 $HTTP_RAW_POST_DATA。”。

    正如 cmets 中的 OP 所指出的那样:

    @Fred-ii- 谢谢,它通过像这样添加 $postdata = file_get_contents("php://input");

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多