- Instant help with your Php coding problems

Get JSON data from POST in PHP

Question:
How to get JSON data from POST in PHP?
Answer:
$rawPostData = file_get_contents("php://input")
$requestData = json_decode($rawPostData);
Description:

Unfortunately, if you want to process a POST request containing JSON data in your PHP code, you cannot use the well-known $_POST superglobal variable. 
So to retrieve JSON data from a POST request, you will have to use another method.

In this case, you can use the php:// wrappers that help access various I/O streams. From these wrappers, php://input helps you to get the data. php://input is a read-only stream that allows you to read raw data from the request body.

So to get the full request body content you can write this:

$rawPostData = file_get_contents("php://input");

And as we get a raw JSON string we can decode it to a JSON object using the json_decode method like this:

$requestData = json_decode($rawPostData);

If you want the result, not as a stdObject but as an associative array then use this code:

$requestData = json_decode($rawPostData, true);
Share "How to get JSON data from POST in PHP?"
Tags:
get, receive, handle, JSON, object, post, request, php
Technical term:
Get JSON data from POST in PHP
Interesting things
ChatGPT in a nutshell