我试图发布以下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']))
始终为false且消息为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://输入流。在第0行的未知中
答案 0 :(得分:1)
如果将发布数据作为json发送,则在api中必须将输入数据解码为数组
$data = json_decode($_POST)
然后继续条件
if (isset($data['name'], $data['email'], $data['password']) {
答案 1 :(得分:1)
注意:这是社区维基的答案。
根据$HTTP_RAW_POST_DATA
http://php.net/manual/en/reserved.variables.httprawpostdata.php
“通常,应使用php://输入而不是$ HTTP_RAW_POST_DATA。”。
OP在评论中也指出:
@ Fred-ii-谢谢,它通过添加像这样的$ postdata = file_get_contents(“php:// input”);