PHP filter_var() Function
filter_var() applies a filter to a value. It is often used to validate common input formats or apply limited sanitization.
Validate an Email Address
$email = "person@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email format";
} else {
echo "Invalid email format";
}
A successful validation confirms that the value matches the filter's format rules. It does not prove that the mailbox exists or belongs to the user.
Validate an Integer
$value = "42";
$number = filter_var($value, FILTER_VALIDATE_INT);
if ($number !== false) {
echo $number;
}
Check against false rather than using a loose truthiness test, because zero is a valid integer result.
Validate a URL
$url = "https://example.com";
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
echo "Valid URL format";
}
URL validation does not make it safe to fetch the URL. Applications that retrieve remote resources must also defend against server-side request forgery and restrict destinations.
Validation vs. Sanitization
Validation checks whether a value meets a rule. Sanitization transforms a value. Neither replaces context-aware output escaping or application-specific business validation.
Summary
Use filter_var() for common format checks, then apply the additional validation and security controls required by your application.