0

I'm executing the following curl command

curl -X POST -H 'Content-Type: application/json' --data '{"x":"1","y":"2"}' http://localhost/test.php

to a PHP script that looks like

<?php
    var_dump($_POST);
    var_dump(file_get_contents('php://input'));
?>

As output I get:

array(0) {
}
string(17) "{"x":"1","y":"2"}"

In short $_POST is empty but the data is kind of there. I guess I could encode the string t JSON but I would prefer to know what's going on. After some online search I can exclude the following issues:

  • I'm on Ubuntu, so I shouldn't have issues with single and double quotes in the curl command.
  • I've checked my php.ini and enable_post_data_reading is enabled and post_max_size = 8M (and not accidentally set to 0, for example). Also confirmed via phpinfo().

UPDATE: As the commenters pointed rightly out, I had simply the wrong expectations that I cat the JSON parameter string automatically as an $_POST array. Not to change my existing code, I followed the post linked above as related to my questions. I added the line:

$_POST = json_decode(file_get_contents('php://input'), true);

And now it works.

Christian
  • 3,239
  • 5
  • 38
  • 79
  • 1
    JSON request bodies are read from `php://input` only. `$_POST` is only populated by `application/x-www-form-urlencoded` request data. I'll find a link for you with more detail – Phil Dec 13 '19 at 04:47
  • 1
    You'll want to use json_decode() as well to read the php://input contents as an object/array – SyntaxLAMP Dec 13 '19 at 09:24

0 Answers0