So, apparently when you're POSTing to PHP with Content-Type: application/json the $_POST variable will not get populated because PHP is not ready to support JSON as input. Because 1999.

  • 5
    True. It's stupid, but luckily for this case there is a quick workaround:

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

    Hopefully you will never have to send files (aka multipart/form-data) with PUT requests. You will see fun there.
  • 2
    Nice first rant. Welcome
  • 2
    @CoffeeAndHate It's worth to mention that this will fail if the string is not valid JSON.

    Another workaround to check JSON:

    function isValidJSON($str) {
    return json_last_error() == JSON_ERROR_NONE;

    $json_params = file_get_contents("php://input");

    if (strlen($json_params) > 0 && isValidJSON($json_params))
    $decoded_params = json_decode($json_params);
  • 1
    @tracktraps Of course, you always have to check for errors and user input. But I just wanted to point the essence of that, without making the post too bulky.

    Not to mention that unicode support for json in php sucks a lot.
  • 0
    All these php rants are making me consider avoiding php and just learn django or flask.
  • 1
    @DVZ96 It sounds worse than it is. Simply use a framework, such as Laravel (I prefer ZF3). This takes away most of the inconsistencies with PHP.
  • 1
    @tracktraps Some basic one, like Slim, should do and is better if you want to have full controll over your app.
  • 0
    @DVZ96 If you use Laravel everything will be fine. It's not that bad when you follow a set of rules.
  • 1

    1 composer require it
    2 follow the guide
    3 be a pro
Your Job Suck?
Get a Better Job
Add Comment