0

I want to send json payload to my PHP webservice. I am testing on advance rest client. I already search similar answers. But it is not helping me. I am sending this json to my php service which is running on localhost.

{
"name":"XXXX",
"password":"YYYYY"
}

I changed the content-type from dropdown to application/json. However sending value as form parameter from advance rest client works fine.But this is not what i want.

My php code is

$name= isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : "";
    $pass= isset($_POST['pass']) ? mysql_real_escape_string($_POST['pass']) : "";

    echo $name;
    echo $pass;

but it is always printing the blank value. I am new to php but found this is the way to receive post params.

Altaf Hussain
  • 5,166
  • 4
  • 30
  • 47
Piyush
  • 21
  • 4
  • $_POST will only be populated if the request is send as `Content-Type` `application/x-www-form-urlencoded` or `multipart/form-data` – if you send it using any other content type, then you need to read the data from `php://input` (f.e. using `file_get_contents`), and then parse it yourself. – CBroe Oct 18 '15 at 13:24
  • are you posting json data to your php webservice ? or please tell how you are sending it. – Sashant Pardeshi Oct 18 '15 at 13:55
  • @SashantPardeshi yes i sent json data in body of request. and the problem was in php code. Now I got the solution using above answers. – Piyush Oct 25 '15 at 10:29
  • @CBroe ya got the point thanks – Piyush Oct 25 '15 at 10:37

1 Answers1

0

I found the solution if any one else facing same issue. To read the json data sent in the request body we can use this method

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    $request_body = file_get_contents('php://input');
    $data = json_decode($request_body);
    $name = isset($data->name) ? mysql_real_escape_string($data->name) : "";
    echo $name
}

Now it will give the correct value.

Piyush
  • 21
  • 4