CodShot
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.

Snippet actions

CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support