PHP Code Examples

Read and Validate a JSON Request Body in PHP

Read JSON sent by an API client, decode it safely, and validate expected fields before processing.

Example

<?php
header('Content-Type: application/json; charset=utf-8');

$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);

if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON body.']);
    exit;
}

$name = trim((string) ($data['name'] ?? ''));

if ($name === '') {
    http_response_code(422);
    echo json_encode(['error' => 'The name field is required.']);
    exit;
}

echo json_encode(['success' => true, 'name' => $name]);

Explanation

JSON request bodies are read from php://input; they are not automatically populated in $_POST.

In production, also enforce a request-body size limit, check the HTTP method and content type, and validate every field against your application rules.

Share this page Help other developers discover this resource.