Middle
Where in PHP is the body of a POST request? How to get data from a form and from a JSON request?
sobes.tech AI
Answer from AI
In PHP, the body of a POST request can be accessed in several ways depending on the data type:
- Form data (Content-Type: application/x-www-form-urlencoded or multipart/form-data)
- Available in the superglobal array
$_POST. - Example:
- Available in the superglobal array
$name = $_POST['name'] ?? null;
$email = $_POST['email'] ?? null;
- JSON format data (Content-Type: application/json)
- The request body can be obtained via the stream
php://input. - Then decode the JSON into an array or object.
- The request body can be obtained via the stream
$json = file_get_contents('php://input');
$data = json_decode($json, true); // true for array
$name = $data['name'] ?? null;
$email = $data['email'] ?? null;
Thus, $_POST is used for form data, and reading from php://input and decoding is used for JSON.