One of the most important rules in web security is: "Never trust user input." Malicious or poorly formatted user inputs can break database queries, cause server crashes, or trigger Cross-Site Scripting (XSS) vulnerabilities. PHP provides a powerful built-in Filter Extension centered around the filter_var() and filter_input() functions designed specifically to validate and sanitize external data.
false on failure.<?php
$emailInput = " vikram.aditya+test@veewom.com ";
// Step 1: Sanitize by removing illegal characters & trimming
$cleanEmail = filter_var(trim($emailInput), FILTER_SANITIZE_EMAIL);
// Step 2: Validate against RFC email standards
if (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email: " . $cleanEmail . "<br>";
} else {
echo "Invalid Email Address provided!<br>";
}
?>
<?php
$studentAge = "21"; // String from form submission
// Validate integer between 18 and 30
$options = [
"options" => [
"min_range" => 18,
"max_range" => 30
]
];
if (filter_var($studentAge, FILTER_VALIDATE_INT, $options) !== false) {
echo "Valid candidate age: $studentAge years.<br>";
} else {
echo "Eligibility Error: Candidate must be between 18 and 30 years.<br>";
}
?>
<?php
$website = "https://veewom.com";
if (filter_var($website, FILTER_VALIDATE_URL)) {
echo "Valid Web Address.<br>";
}
$clientIP = "192.168.1.1";
if (filter_var($clientIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
echo "Valid IPv4 Network Address.";
}
?>
| Filter Constant | Type | Validation / Sanitization Purpose |
|---|---|---|
FILTER_VALIDATE_EMAIL | Validate | Validates standard RFC email address format. |
FILTER_VALIDATE_INT | Validate | Checks if value is a valid integer. |
FILTER_VALIDATE_FLOAT | Validate | Checks if value is a floating point number. |
FILTER_VALIDATE_URL | Validate | Validates standard HTTP/HTTPS URL address. |
FILTER_VALIDATE_IP | Validate | Validates IPv4 or IPv6 network addresses. |
FILTER_SANITIZE_EMAIL | Sanitize | Removes all characters except letters, digits, and special email symbols. |
FILTER_SANITIZE_URL | Sanitize | Removes all illegal URL characters. |
High-Frequency Exam Question:
Q: Why must you check filter_var($val, FILTER_VALIDATE_INT) !== false with strict comparison?
A: If the integer being tested is 0, loose comparison if (filter_var(0, FILTER_VALIDATE_INT)) evaluates 0 to false! Strict comparison (!== false) guarantees that valid integers of value 0 are recognized correctly.
Exercise 30.1: Write a script that validates user input for a website URL, rejecting it if it lacks an "https://" scheme.
Exercise 30.2: Write a function that accepts an array of raw form strings and sanitizes all of them using filter_var_array().