Reputation: 1595
I am trying to POST json data from commandline with curl to a php script. But I can't figure out how to receive the posted json on the Server site (php)
This is what I have tried so far:
commandline:
curl -H "Content-Type: application/json" -X POST -i -d '{"token":"xyz"}' http://localhost/api/users.php
users.php
//Receive the RAW post data.
$content = file_get_contents("php://input");
echo $content;
// try to decode json
$decoded = json_decode($content);
if($decoded){
echo "success";
echo $decoded['token'];
}
else{
echo "failed";
}
The result that I get is:
'{token:xyz}'
failed
I also tried to escape the " in the curl call like:
curl -H "Content-Type: application/json" -X POST -i -d '{\"token\":\"xyz\"}' http://localhost/api/users.php
but then I get almost the same result:
'{"token":"xyz"}'
failed
So my Problem is that the php script fails to convert the received json data.
What am I doing wrong?
EDIT (Solved):
Call cmd curl command with double quotes and escape quotes in between:
curl -H "Content-Type: application/json" -X POST -i -d "{\"token\":\"xyz\"}" http://localhost/api/users.php
Upvotes: 0
Views: 310
Reputation: 652
Seems ok, but after testing your example it seems to be working only if i put double quotes around the post data. Try it.
Upvotes: 1