APIs

PHP JSON API Snippets

Bounded JSON request body reader with exception-based decoding.

Overview

Bounded JSON request body reader with exception-based decoding.

Code example

<?php
declare(strict_types=1);
function readJsonBody(int $maxBytes=1048576): array {
    $raw=file_get_contents('php://input',false,null,0,$maxBytes+1);
    if($raw===false||strlen($raw)>$maxBytes) throw new RuntimeException('Body too large or unreadable.');
    $data=json_decode($raw,true,512,JSON_THROW_ON_ERROR);
    if(!is_array($data)) throw new UnexpectedValueException('Expected JSON object or array.');
    return $data;
}

How to use it

Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.

Notes

The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.