Catch and parse JSON Post data in PHP
A few days ago I’ve been working a project which, as many other projects out there today, communicates with some external APIs. At some point, in order to perform some tests, I had to write an API endpoint within my project itself to fake the actual external API. I need to mention that the external API was expecting application/json content type, so basically the curl setup looked like this:
timeout_limit ); curl_setopt( $ch, CURLOPT_ENCODING, '' ); curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 ); curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ) ); // .
The issue was that when I’ve been trying to catch the POST data and use it, I was getting null as a value for both $_POST or $_REQUEST , and I couldn’t understand why 🤔. Apparently (and maybe many of you already knew that), if the data is sent as multipart/form-data or application/x-www-form-urlencoded then yes, you can use PHP globals $_POST or $_REQUEST to catch and use that data. But, if the data is sent as application/json , then prior to PHP 5.6 you could’ve use $HTTP_RAW_POST_DATA to grab the raw POST data, or (and based on PHP docs this is the preferable way to do it) use the php://input — a read-only stream that allows you to read raw data from the request body. So, as a result I ended up grabbing the POST data like this:
Php get posted json
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
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");
Now, let’s take a look at an example where we attempt to receive and validate JSON POST data:
//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:
- 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.
- We validate the content type. In this case, we want it to be application/json.
- We retrieve the raw POST data from the php://input stream.
- We attempt to decode the contents of the POST data from JSON into a PHP associative array.
- 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.
- After that, we can process the associative array.
Hopefully, you found this tutorial to be helpful!
Read JSON request data with PHP
While working on an API project, I realised that I actually didn’t know how to receive JSON data in the request body with PHP. Turns out it’s really simple with the php://input stream.
Most projects we work on with PHP rely on forms to receive data. That’s what the $_POST superglobal is for: it contains all information passed via HTTP POST when sending data with content type application/x-www-form-urlencoded or multipart/form-data .
But what if you use the application/json content type? Up until PHP 5.6 we could use the $HTTP_RAW_POST_DATA superglobal, but this has been deprecated. Instead we should use the php://input stream to read raw data from the request body.
Below is an example script. The comments explain what’s happening:
// Only allow POST requests if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') < throw new Exception('Only POST requests are allowed'); > // Make sure Content-Type is application/json $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : ''; if (stripos($content_type, 'application/json') === false) < throw new Exception('Content-Type must be application/json'); > // Read the input stream $body = file_get_contents("php://input"); // Decode the JSON object $object = json_decode($body, true); // Throw an exception if decoding failed if (!is_array($object)) < throw new Exception('Failed to decode JSON object'); > // Display the object print_r($object);
Let’s give this a quick whirl. Save the example as script.php and start the standalone PHP server with php -S localhost:8080 script.php .
Now let’s send it a POST request containing JSON data using cURL:
curl -X POST \ -d '' \ -H "Content-Type: application/json" \ http://localhost:8080
Your JSON object should be printed out:
Array ( [foo] => Array ( [0] => bar [1] => baz ) )