Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read JSON from the request body

Short answer

Data sent as JSON does not get into $_POST. Read the request body from php://input:

<?php
 
// api.php
 
$data = json_decode(file_get_contents('php://input'), true);
 
echo $data['name'] ?? 'no name';

With validation

Invalid JSON should produce a 400 response:

<?php
 
// api.php
 
header('Content-Type: application/json');
 
try {
    $data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
    http_response_code(400);
    exit(json_encode(['error' => 'Invalid JSON']));
}
 
echo json_encode(['received' => $data]);

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.