0

I am trying to read data send by curl request but I cant able to read that. example

curl -x post -d '{user:"test", pwd:"123"}' http://localhost/api/login/

and in PHP code

$user = $_POST['user'];

but always I am getting a null value, how to fix this issue?

Gilson PJ
  • 3,443
  • 3
  • 32
  • 53

1 Answers1

2

You can specify the post name in curl. Right now you're submitting JSON, but without a name. (Link to curl man pages)

-d data={JSON}

Then in php you can load and decode the JSON: (Link to json_decode in the php manual)

$data = json_decode($_POST['data'], true);
$user = $data['user'];

If you want to continue sending data without using key/value pairs, you can keep your existing implementation of curl and use the following in PHP:

$data = @file_get_contents("php://input");
$json = json_decode($data, true);

This was taken from: XMLHTTP request passing JSON string as raw post data

Community
  • 1
  • 1
Evan
  • 457
  • 3
  • 22
  • first of all thanks for answering my question.is there any other way to read the data without assigning to a variable?becoz the customer wants the api calls like the exact way i have specified. – Gilson PJ Dec 27 '15 at 23:15
  • I've just updated the solution to read from php://input so that you don't need to modify the API call – Evan Dec 28 '15 at 00:17