简体   繁体   中英

cmd curl json to php script

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

Seems ok, but after testing your example it seems to be working only if i put double quotes around the post data. Try it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM