bhylu.com

Advertisements

PHP Form Validation

Required-field validation should distinguish a missing value from a blank or wrongly shaped value. Return errors that identify the field without exposing private implementation details.

How it works

Validate a bounded string after confirming it is actually a string. Trimming is appropriate for this human-entered name, but would be a different policy for a password where whitespace can be significant. Build a structured error response so a client can attach feedback to the appropriate control. Validation is not authorisation and does not establish that an item is available.

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 required-fields.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 8.2+ · required-fields.php

<?php
declare(strict_types=1);

header("Content-Type: application/json; charset=utf-8");
if (($_SERVER["REQUEST_METHOD"] ?? "GET") !== "POST") { http_response_code(405); header("Allow: POST"); echo json_encode(["error"=>"Use POST"]); exit; }
$raw = $_POST["item"] ?? null;
$item = is_string($raw) ? trim($raw) : "";
if ($item === "" || mb_strlen($item, "UTF-8") > 60) {
    http_response_code(422); echo json_encode(["errors"=>["item"=>"Use 1 to 60 characters"]]); exit;
}
echo json_encode(["item"=>$item], JSON_THROW_ON_ERROR);

Expected result

{"item":"Rake"}

A blank or array-shaped value reaches the same bounded-field error. Accepted text is stored separately from the raw field, making it clear which representation later code should use. The length limit is a character count in the stated encoding; also validate encoding when your input boundary cannot guarantee UTF-8.

Requests to check

  • POST required-fields.php → status 200; form fields: item.
  • POST required-fields.php → status 422; form fields: item.

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.

Advertisements