0
0
PhpHow-ToBeginner · 3 min read

How to Use filter_var in PHP: Syntax and Examples

Use filter_var in PHP to validate or sanitize data by passing the value and a filter type like FILTER_VALIDATE_EMAIL or FILTER_SANITIZE_STRING. It returns the filtered data or false if validation fails.
📐

Syntax

The filter_var function takes three parameters:

  • value: The data you want to check or clean.
  • filter: The type of filter to apply, such as validation or sanitization.
  • options (optional): Extra settings for the filter.

It returns the filtered value or false if validation fails.

php
filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed
💻

Example

This example shows how to validate an email and sanitize a string using filter_var.

php
<?php
$email = "user@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email: $email\n";
} else {
    echo "Invalid email.\n";
}

$dirtyString = "Hello <b>World</b>!";
$cleanString = filter_var($dirtyString, FILTER_SANITIZE_STRING);
echo "Sanitized string: $cleanString\n";
?>
Output
Valid email: user@example.com Sanitized string: Hello World!
⚠️

Common Pitfalls

Common mistakes include:

  • Using filter_var without checking for false which means validation failed.
  • Confusing sanitization with validation; sanitization cleans data but does not guarantee it is valid.
  • Using deprecated filters like FILTER_SANITIZE_STRING in PHP 8.1+; prefer alternatives like htmlspecialchars.
php
<?php
// Wrong: Not checking validation result
$email = "invalid-email";
$result = filter_var($email, FILTER_VALIDATE_EMAIL);
echo "Result: $result\n"; // Prints nothing because result is false

// Right: Check if validation passed
if ($result === false) {
    echo "Email is invalid.\n";
} else {
    echo "Email is valid: $result\n";
}
?>
Output
Result: Email is invalid.
📊

Quick Reference

Filter TypeDescription
FILTER_VALIDATE_EMAILChecks if the value is a valid email address
FILTER_VALIDATE_INTChecks if the value is a valid integer
FILTER_SANITIZE_STRINGRemoves tags and encodes special characters (deprecated in PHP 8.1+)
FILTER_SANITIZE_EMAILRemoves all illegal characters from email
FILTER_VALIDATE_URLChecks if the value is a valid URL
FILTER_SANITIZE_URLRemoves illegal URL characters

Key Takeaways

Use filter_var to validate or sanitize data safely in PHP.
Always check if filter_var returns false to handle invalid data.
Sanitization cleans data but does not guarantee it is valid.
Avoid deprecated filters like FILTER_SANITIZE_STRING in new PHP versions.
Use appropriate filters for your data type to get correct results.