PHP filters provide a secure and efficient way to validate and sanitize user input. With functions like filter_var(), filter_input(), and filter_var_array(), you can clean form data, validate emails, numbers, URLs, and more. Filters help prevent common vulnerabilities like XSS and injection attacks. You can also apply filters with custom options and ranges. This guide covers practical and secure usage of PHP filters in modern applications.
1. Filter Types
- Sanitization: Removes unwanted characters.
- Validation: Checks if data matches a specific format.
2. filter_var()
– Core Function
form_handler.php
$value = "test@example.com";
if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo "Valid email!";
}
3. Filter Examples
Use Case | Code Example |
---|---|
Validate email | FILTER_VALIDATE_EMAIL |
Validate integer | FILTER_VALIDATE_INT |
Sanitize string | FILTER_SANITIZE_STRING (deprecated in PHP 8.1) |
Validate IP | FILTER_VALIDATE_IP |
Sanitize email | FILTER_SANITIZE_EMAIL |
4. With Options and Flags
Example: Validate integer in range
form_handler.php
$age = "25";
$options = [
"options" => ["min_range" => 18, "max_range" => 40]
];
if (filter_var($age, FILTER_VALIDATE_INT, $options)) {
echo "Age is valid!";
}
Example: Sanitize URL and strip invalid characters
submit_form.php
, contact.php
$url = "https://example.com/hello?test=<script>";
$cleanUrl = filter_var($url, FILTER_SANITIZE_URL);
echo $cleanUrl;
5. filter_input()
– Superglobal Filtering
login.php
, register.php
, contact.php
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email) {
echo "Valid POST email!";
}
You can also use INPUT_GET
, INPUT_COOKIE
, INPUT_SERVER
, INPUT_ENV
.
6. Using filter_var_array()
To validate multiple fields at once:
register.php
, update_profile.php
$data = [
"email" => "test@example.com",
"age" => "25"
];
$filters = [
"email" => FILTER_VALIDATE_EMAIL,
"age" => [
"filter" => FILTER_VALIDATE_INT,
"options" => ["min_range" => 18, "max_range" => 60]
]
];
$result = filter_var_array($data, $filters);
print_r($result);
Summary
Function | Purpose |
---|---|
filter_var() |
Validate or sanitize a single value |
filter_input() |
Filter value from input (POST/GET) |
filter_var_array() |
Filter multiple values at once |
FILTER_VALIDATE_* |
For validation |
FILTER_SANITIZE_* |
For sanitization |