PHP filter validation functions are used to validate and sanitize user input before processing. This helps prevent security risks like SQL Injection and XSS attacks.
The filter_var() function validates or sanitizes a single variable using predefined filters.
// Demonstrating PHP filter validation and sanitization
<?php
$email = "john.doe@example.com";
$url = "https://www.example.com";
$age = "25";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "$email is a valid email address.
";
}
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "$url is a valid URL.
";
}
$dirty_string = "<h1>Welcome!</h1>";
$sanitized_string = htmlspecialchars($dirty_string);
echo "Sanitized string: $sanitized_string
";
if (filter_var($age, FILTER_VALIDATE_INT)) {
echo "$age is a valid integer.
";
}
?>
The script validates email, URL, and integer values while sanitizing HTML tags from strings.
Try replacing values with invalid email or URL strings and observe validation results.