We all know that $_POST is used to collect post data in PHP. That’s true. But when we try to get JSON post data using $_POST then it fails.
Recently I was working on project and need to receive JSON POST with PHP. I had expected that JSON POST data in $_POST superglobal variable but variable was empty.
Then how can we receive JSON POST data using PHP.
Finally to receive JSON string, I used php://input along with file_get_contents function.
Let’s see
// takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
php://input is used to read raw data from the request body.
File_get_contents function is used to read a file source and returns it as PHP string.
So we can write a single line of code to get body of POST in PHP. Have a look.
// Receive the JSON Post data in form of array
$data = json_decode( file_get_contents( 'php://input' ), true );
Read :
Send Form Data as JSON via AJAX with JQuery
How to POST JSON Data With PHP cURL
So you have learned that JSON POST data can not be received using $_POST variable. If you have any query regarding this article, feel free to comment.