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:
- 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.
0 comments:
Post a Comment