Example
<?php
$errors = [];
$name = trim($_POST['name'] ?? '');
$ageInput = $_POST['age'] ?? '';
if ($name === '') {
$errors['name'] = 'Name is required.';
}
$age = filter_var($ageInput, FILTER_VALIDATE_INT);
if ($age === false || $age < 18 || $age > 120) {
$errors['age'] = 'Enter an age between 18 and 120.';
}
if ($errors === []) {
// Continue with the validated values.
}
Explanation
Validation checks whether data meets application rules. Sanitization changes data; it should not be used as a substitute for validation.
Best practices
Validate on the server, display errors next to the relevant fields, escape values when redisplaying them, and use database constraints as an additional integrity layer.