PHP JSON Request Bodies
A JSON request body is different from form fields in $_POST. Read it through the appropriate input stream, enforce limits and validate the decoded shape.
How it works
This lab requires POST with application/json, reads a bounded amount and rejects malformed or incorrectly shaped data. The content type check does not make the content trustworthy. A real state-changing endpoint must also authenticate and authorise the operation and apply its browser-request/CSRF policy. This demonstration only validates a quantity and echoes an accepted representation without saving a loan.
Run it locally
Save this standalone lab file in a separate local folder. Start a PHP development server on an unused loopback port, for example php -S 127.0.0.1:8090 -t . . Open the shown filename through that server, not a file URL. Exercise GET and POST as described. This is not a POST endpoint on Bhylu, and the built-in development server is not a production server.
php -l json-request.php
php -S 127.0.0.1:8090 -t .Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
header("Content-Type: application/json; charset=utf-8");
if (($_SERVER["REQUEST_METHOD"] ?? "GET") !== "POST") { http_response_code(405); echo '{"error":"Use POST"}'; exit; }
$type = strtolower(trim(explode(";",$_SERVER["CONTENT_TYPE"] ?? "")[0]));
if ($type !== "application/json") { http_response_code(415); echo '{"error":"Use JSON"}'; exit; }
$raw = file_get_contents("php://input",false,null,0,4097);
if ($raw === false || strlen($raw)>4096) { http_response_code(413); echo '{"error":"Body too large"}'; exit; }
try { $data = json_decode($raw,true,16,JSON_THROW_ON_ERROR); } catch (JsonException $error) { http_response_code(400); echo '{"error":"Malformed JSON"}'; exit; }
if (!is_array($data) || !is_int($data["quantity"] ?? null) || $data["quantity"] < 1 || $data["quantity"] > 10) { http_response_code(422); echo '{"error":"Invalid quantity"}'; exit; }
echo json_encode(["accepted_quantity"=>$data["quantity"]]);
Expected result
{"accepted_quantity":3} for a valid JSON quantity.The endpoint treats malformed syntax, wrong media type and invalid business shape as separate cases. The read bound applies even if a client lies about Content-Length. The example’s small maximum is deliberate and should be adjusted only after considering memory, parsing depth and the real operation.
Requests to check
POST json-request.php→ status 200; JSON body.POST json-request.php→ status 400; JSON body.POST json-request.php→ status 422; JSON body.POST json-request.php→ status 415; form fields: quantity.
Use a local browser form or HTTP client. A CSRF token from one session does not authorise a different session. The automated review uses actual HTTP requests, not just command-line output.
Check the official PHP manual for detailed version and API contracts.