QA
Intermediate LevelPHP 8+

How do you validate and sanitize user input securely using filter_var()?

❓ Interview Prompt: Explain filter_var() input validation (FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT) vs sanitization filters.

Validating and sanitizing incoming user input is essential for web security. PHP provides C-level input filtering via 'filter_var()'.

1. Validation Filters (Check input format):

•
'FILTER_VALIDATE_EMAIL': Returns valid email string, or 'false' if invalid.
•
'FILTER_VALIDATE_INT': Validates integers, supporting range options ('min_range', 'max_range').
•
'FILTER_VALIDATE_URL': Validates HTTP/HTTPS URLs.

2. Sanitization Filters (Strip bad characters):

•
'FILTER_SANITIZE_NUMBER_INT': Strips all characters except digits and '+/-'.
•
'FILTER_SANITIZE_SPECIAL_CHARS': Encodes HTML tags to prevent XSS payloads.

Code Implementation Example

php
<?php
$email = $_POST['email'] ?? '';
$age = $_POST['age'] ?? '';

// 1. Validate Email Format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format!";
}

// 2. Validate Integer within range (18 to 99)
$validAge = filter_var($age, FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 18, 'max_range' => 99]
]);

if ($validAge === false) {
    echo "Age must be an integer between 18 and 99!";
}
💡Validating email formats and integer ranges securely using filter_var().
🎯 Interview Key Takeaway

Use filter_var() with validation filters (FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT) for safe input validation.

#filter_var#Validation#Sanitization#Security#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?