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:

//Receive the RAW post data via the php://input IO stream.
$content = file_get_contents("php://input");

Pretty simple, right?

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

<?php

//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
    throw new Exception('Content type must be: application/json');
}

//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);

//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
    throw new Exception('Received content contained invalid JSON!');
}

//Process the JSON.

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!