Navneet Krishna
Navneet Krishna

Reputation: 5017

Cant post data in body in PHP

iam trying to post the following json data

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

in the body of my 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);
}
?>

my problem is that if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) is always false and the messageRequired parameters (name, email or password) is missing! is shown

In the wampserver log, error is given as

PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0

Upvotes: 0

Views: 223

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74220

Note: This is a community wiki answer.

As per the manual on $HTTP_RAW_POST_DATA

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

"In general, php://input should be used instead of $HTTP_RAW_POST_DATA.".

As noted by the OP in comments also:

@Fred-ii- thanks, it worked by adding like this $postdata = file_get_contents("php://input");

Upvotes: 1

neattom
neattom

Reputation: 364

if sending post data as json, in api you must decode input data to array

$data = json_decode($_POST)

and after then continue with the condition

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

Upvotes: 1

Related Questions