Validation
On this page
Why Server-side Validation Is Mandatory
Client-side validation improves UX but can be bypassed. The server must validate every request to protect data integrity and security.
Basic Validation Example
Validate required fields and normalize input (trim, type cast).
<?php
$email = trim($_POST['email'] ?? '');
$age = (int)($_POST['age'] ?? 0);
$errors = [];
if ($email === '') {
$errors[] = 'Email is required';
}
if ($age < 13) {
$errors[] = 'Age must be at least 13';
}
if ($errors) {
echo 'Validation failed: ' . implode(', ', $errors);
exit;
}
echo 'OK';
Validate Email Properly
Use filter_var for common types like email.
<?php
$email = trim($_POST['email'] ?? '');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email';
exit;
}
Whitelist Validation (Best Practice)
When validating enums (role, status, sort order), prefer a whitelist. This prevents unexpected values.
<?php
$status = $_POST['status'] ?? 'draft';
$allowed = ['draft', 'published', 'archived'];
if (!in_array($status, $allowed, true)) {
echo 'Invalid status';
exit;
}
Validation Structure (Production Style)
As your app grows, you should centralize validation into functions/services so controllers stay thin.
<?php
function validateCreateItem(array $input): array {
$errors = [];
$title = trim($input['title'] ?? '');
if ($title === '') {
$errors[] = 'Title is required';
}
return $errors;
}
Production Tip
Validate for correctness and safety: required fields, length limits, allowed characters, and allowed values. Always fail safely with user-friendly messages and detailed logs for developers.