Overview
Validation checks whether input has the shape and meaning the application expects. Perform it at the boundary where data enters the system, before business logic or database operations use it. Validation is not a substitute for output escaping or authorization.
Validate by expected type
Use explicit rules for integers, email addresses, dates, enumerations and identifiers. Avoid assuming that a value is safe because it came from a form or a hidden field. For numeric input, parse and range-check rather than relying on loose comparisons.
<?php
$rawId = $_POST['id'] ?? null;
$id = filter_var($rawId, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1]
]);
if ($id === false) {
http_response_code(422);
exit('A valid identifier is required.');
}
Validate structure and business rules
A date may be syntactically valid but outside the allowed booking window. A quantity may be an integer but exceed inventory. Keep format checks and domain rules explicit, and return useful field-level errors without exposing internal details.
Treat JSON and headers as input
Check the content type, enforce a request-size limit and handle JSON decoding errors. Do not trust a client-provided filename, MIME type, role, price or account identifier. Derive sensitive values from the authenticated server-side context.
Validate, then encode on output
Validation does not make text safe for every context. Escape HTML when rendering HTML, use parameterized SQL for queries and encode data for JavaScript or URLs according to the output context.
Official references
PHP filter functions PHP JSON handling
Validate according to the field's meaning
Validation is not the same as escaping. Validate identifiers as integers, email addresses as email addresses, dates against an expected format and uploaded files using upload-specific checks. Normalize only when the transformation is part of the field's contract.
<?php
$email = trim((string)($_POST['email'] ?? ''));
if ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Enter a valid email address.';
}
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
$page = ($page !== false && $page !== null && $page > 0) ? $page : 1;
For JSON requests, decode with exception handling and verify that the result has the expected structure. Reject unexpected types rather than silently converting arrays to strings.
Apply limits and allowlists
Set maximum lengths for text fields, restrict enumerated values to an allowlist and limit pagination ranges. For dates, parse with an exact format and inspect parsing warnings. For numeric business values, validate range and precision as well as type.
Validate again on the server
Browser-side validation improves usability but can be bypassed. Every state-changing request must be validated server-side. Then use parameterized SQL for database values and context-aware output escaping when rendering HTML. Those are separate controls.
Error responses
Return useful field-level messages without exposing stack traces, SQL, filesystem paths or internal configuration. Log diagnostic details privately with a request identifier so support staff can correlate the event.