PHP
Public
PHP Read JSON Request Body
Read and validate a JSON request body in PHP.
#php
#api
#json
#validation
PHP
<?php
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON body.']);
exit;
}
$title = trim($data['title'] ?? '');
if ($title === '') {
http_response_code(422);
echo json_encode(['error' => 'Title is required.']);
exit;
}
Notes
Check json_last_error before trusting decoded request data.