Receiving JSON POST data via PHP.

In a previous tutorial, I showed how to send JSON data via POST in PHP. This led to somebody asking me how to receive JSON POST data with PHP.

To receive RAW post data in PHP, you can use the php://input stream like so:

Pretty simple, right?

Now, let’s take a look at an example where we attempt to receive and validate JSON POST data:

A drill-down of the code sample above:

  1. We validate the request type by checking to see if it is POST. This will prevent the script from trying to process other request types such as GET.
  2. We validate the content type. In this case, we want it to be application/json.
  3. We retrieve the raw POST data from the php://input stream.
  4. We attempt to decode the contents of the POST data from JSON into a PHP associative array.
  5. We check to see if the result is an array. If it is not an array, then something has gone wrong. To debug the issue even further, be sure to check out this article on JSON error handling in PHP.
  6. After that, we can process the associative array.

Hopefully, you found this tutorial to be helpful!

Facebook Comments