PHP: Receive raw POST data.

This is a short guide on how to receive raw POST data in PHP. This is useful if you intend on receiving JSON or XML via a POST request.

In most day-to-day cases, we tend to access POST data like so:

//Retrieving a POST field in PHP
$name = $_POST['name'];

However, in certain cases, you may need to access the POST request’s body as a whole. In those cases, you will need to access the php://input stream.

The php://input stream.

PHP has a number of I/O streams that you can access. In this case, we are particularly interested in the php://input stream.

Take a look at the following example:

//Get the raw POST data
$postBody = file_get_contents("php://input");

In the code above, we used the file_get_contents function to read the php://input stream into a PHP variable called $postBody.

If a POST request is sent to the script above, the entire body of the request will be assigned to the $postBody variable.

For example: When I sent three POST parameters to the script in question, the php://input stream returned the following string:

name=Patrick&age=31&nationality=Irish

Note that if no POST data is present, the code above will return a blank string.

Don’t use $HTTP_RAW_POST_DATA.

$HTTP_RAW_POST_DATA is a predefined PHP variable that can be configured to contain raw POST data. However, the variable was officially deprecated in PHP 5.6 and completely removed as of PHP 7.0.

Besides the fact that it is no longer supported, there is also the drawback of having to mess around with .ini directives in order to get it working. This is because the feature is turned off by default on most PHP installations.

The feature relies on the always_populate_raw_post_data directive being set to 1. However, the default value for this directive is 0 (off).

Long story short: You should use the input stream approach instead.