Tuesday, February 1, 2022

[SOLVED] json_decode deserialization error with curl

Issue

I've created a Rest API that is working well, but I noticed a strange thing. For deserializing the content sent by the client I use this code:

var_dump(json_decode(file_get_contents("php://input"), true));

If I send a request with POSTMAN (Chrome Extension), all is working well, see:

enter image description here

but if I use curl with MINGW64, I'll get NULL:

enter image description here

Now in both cases, I checked the encoding type which was with this code:

$content = file_get_contents("php://input");
$encode =  mb_detect_encoding($content, "auto");
$json = mb_convert_encoding($content, $encode);
var_dump($json);

and this returns UTF-8

I don't understand why, with curl MINGW64, the console is not working, yet with the extension, or is working. What's happeni.g?

UPDATE

I've executed this function: json_last_error(), and it returned 5. On this site, I saw that the number corresponds to an error:

5 = JSON_ERROR_UTF8

But I have no idea what is wrong.


Solution

Since you are submitting JSON data in the body, you need to tell the server the content-type, otherwise cURL is sending it as application/x-www-form-urlencoded.

Additionally, any UTF-8 characters need to be encoded in \uXXXX format to have a valid JSON string.

Try:

curl -i -H "token: company" \
-H "Content-type: application/json" \
-d '{"Code": "R89d", "Descri": "Questo \u00E8 un test"}' \
-X PUT http://localhost/api/customer/add

Edit:

Not sure what you're starting out with, but you can use the following two commands to supply cURL with a proper JSON string.

var=$(php -r 'echo json_encode(["Code" => "R89d", "Descri" => "Questo รจ un test"]);')
curl -v -H "Content-type: application/json" -d "$var" http://sandbox/test.php


Answered By - drew010
Answer Checked By - Pedro (WPSolving Volunteer)