Application Security

Validate and Normalize User Input in PHP

Build a consistent server-side input validation strategy for strings, integers, email addresses, and enumerated values.

Validate according to purpose

Define what each field may contain, its length, and its business rules. Do not apply one generic sanitizer to every input.

Validate an integer

$quantity = filter_var(
    $_POST['quantity'] ?? null,
    FILTER_VALIDATE_INT
);

if ($quantity === false || $quantity < 1 || $quantity > 100) {
    http_response_code(422);
    exit('Invalid quantity.');
}

Validate an email format

$email = trim($_POST['email'] ?? '');

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    exit('Invalid email address.');
}

Format validation does not prove mailbox ownership. Use verification when ownership matters.

Validate enumerated values

$allowed = ['draft', 'published'];
$status = $_POST['status'] ?? '';

if (!in_array($status, $allowed, true)) {
    http_response_code(422);
    exit('Invalid status.');
}

Keep validation and output encoding separate. Use prepared statements for database values and context-appropriate escaping for HTML.