Backend Coder Logo

How to get JSON POST Data in PHP

Published: 9th February 2015

In PHP it's easy to get the POST data from forms via the $_POST global variable, but in regard to JSON data that is posted from a Front-end framework such as AngularJS, a different method is needed.

In this case, the data is sent as raw data, so we need to extract the data as follows:


if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
  $data = json_decode(file_get_contents("php://input"));
  print_r($data);
}

If the JSON data cannot be decoded, then the constant NULL will be returned as $data.

Assume that the data is not to be trusted. So before you act on the data, test it for validity. For example, test that an expected number is actually a number in your expected range.

The decoded data will be of type object. To turn it into an Array, you can cast it to type array. Here is some code demonstrating this:


<?php

echo "<pre>\n";

$data = (object) array(
	'name' => 'John',
	'age' => 42
);

print_r($data);

printf("Name: %s Age: %s\n\n", $data->name, $data->age);

$data = json_encode($data);

echo "JSON data: $data\n\n";

$data = json_decode($data);

print_r($data);

$data = (array) $data; // cast (convert) the object to an array

print_r($data);

printf("Name: %s Age: %s\n\n", $data['name'], $data['age']);

?>

The output looks like this:

stdClass Object
(
    [name] => John
    [age] => 42
)
Name: John Age: 42

JSON data: {"name":"John","age":42}

stdClass Object
(
    [name] => John
    [age] => 42
)
Array
(
    [name] => John
    [age] => 42
)
Name: John Age: 42

Transcoding Complex Objects

The basic json_encode and json_decode PHP functions are rather primitive. They don't work perfectly when working with nested, and mixed Objects and Arrays.

If the first level of the data structure is an Array, then it will be correctly encoded as an Array, but more deeply-nested arrays will be encoded as Objects by default. So you have to bear this in mind when decoding the JSON data i.e. your code that uses the data should type-cast the relevant objects to Arrays where it is necessary.

The latest versions of PHP have a new way to handle JSON data which may overcome this problem with something like a Schema Template, but I haven't looked into it yet since I want to support the older versions of PHP5.