W3docs

Issue reading HTTP request body from a JSON POST in PHP

In PHP, you can read the body of an HTTP request using the file_get_contents('php://input') function.

In PHP, you can read the body of an HTTP request using the file_get_contents('php://input') function. To parse the body as a JSON object, you can use the json_decode() function. Here's an example of how you can do this for a JSON POST request:

Example of reading the body of an HTTP request using the file_get_contents('php://input') function for a JSON POST request in PHP

<?php

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

The json_decode() function takes the raw input string and converts it into a PHP associative array. The second parameter of json_decode() is a boolean that tells the function whether or not to return an associative array. In this case, it is set to true.

Make sure your PHP version is at least 5.2. Note that the json extension is bundled by default in PHP 5.2+ and rarely needs manual php.ini configuration.

Also, you should check if the POST request has the correct format and content-type header. In some server environments, $_SERVER['CONTENT_TYPE'] may be empty, so checking $_SERVER['HTTP_CONTENT_TYPE'] or using getallheaders() can be more reliable.

Example of checking if the post request is coming with correct format and correct content-type header in PHP

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $contentType = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
  if ($contentType === 'application/json') {
    $input = file_get_contents('php://input');
    if ($input !== '') {
      $data = json_decode($input, true);
      if (json_last_error() === JSON_ERROR_NONE) {
        // do something with $data
      } else {
        // handle malformed JSON
      }
    } else {
      // handle empty input
    }
  } else {
    // handle invalid content-type
  }
} else {
  // handle invalid request
}