Validating and sanitizing external data is one of the most important aspects of web security. You should **never trust user input**. PHP filters are used to check if the data is in the correct format (Validation) and to remove illegal characters (Sanitization).
true or false.The filter_var() function is the primary way to use filters in PHP. It takes the variable you want to check and the type of filter to apply.
<?php
$email = "john.doe@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
<?php
$url = "https://www.redohub.com";
// Remove illegal characters from URL
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate URL
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
| Filter Name | Type | Description |
|---|---|---|
FILTER_VALIDATE_INT |
Validation | Validates an integer. |
FILTER_VALIDATE_IP |
Validation | Validates an IP address. |
FILTER_SANITIZE_EMAIL |
Sanitization | Removes all illegal characters from an email. |
FILTER_SANITIZE_SPECIAL_CHARS |
Sanitization | Escapes special characters (like <, >, &). |
FILTER_SANITIZE_STRING is deprecated as of PHP 8.1. Use htmlspecialchars() instead to prevent Cross-Site Scripting (XSS) attacks.
filter_input() to get and filter a variable directly from $_GET, $_POST, or $_COOKIE.