PHP Filters
Learn how to validate and sanitize incoming data safely using PHP's built-in filter_var() function and its filter constants.
Introduction
Any time your PHP script accepts data from outside — a form field, a URL parameter, an uploaded file name — that data cannot be trusted. It might be malformed, missing, or deliberately malicious. PHP's filter extension gives you a consistent, built-in way to check and clean that data before you use it.
In this lesson you will learn the filter_var() function, the difference between validating data and sanitizing it, and how to apply both to a small real-world form.
- Why filtering incoming data matters.
- How filter_var() works and how to call it.
- The difference between validation and sanitization.
- The most commonly used validation and sanitization filters.
- How to validate a form's email and age fields together.
Why Filter Data?
A classic rule in web development is: never trust user input. A visitor can type anything into a form field, tamper with a URL, or send a request that bypasses your HTML entirely. Without checking that data, your application can crash, store garbage, or become vulnerable to attacks like SQL injection or cross-site scripting.
PHP's filter functions were built specifically to make checking and cleaning external data quick and consistent, instead of writing ad-hoc regular expressions and if-statements every time.
Filtering usually happens right after you receive data — from $_GET, $_POST, $_COOKIE, or any other external source — and before that data touches your business logic or database.
The filter_var() Function
filter_var() takes a value and a filter, and returns either the filtered result or false if the value fails validation. Its basic signature is filter_var($variable, $filter, $options).
<?php
$email = "jane@example.com";
$result = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($result !== false) {
echo "Valid email: $result";
} else {
echo "Invalid email address.";
}Valid email: jane@example.comIf the email were malformed — missing an @ symbol, for example — filter_var() would return the boolean false instead of a string, which is why you should always compare with !== false rather than a loose truthy check (an empty string or "0" could otherwise be misread as failure).
Validating vs Sanitizing
These two words are used constantly in PHP's documentation, and it is worth being precise about what each means.
Validating
- Checks whether data is well-formed
- Returns the value unchanged if valid
- Returns false if the data fails the check
- Does not modify the data itself
- Example: is this a real email address?
Sanitizing
- Cleans up data by removing or encoding unwanted parts
- Always returns a (possibly modified) value
- Never returns false
- Changes the data itself
- Example: strip HTML tags from a comment
A good rule of thumb: validate data you expect to be strictly correct (like an email or an age), and sanitize data that is free-form text a user might type carelessly (like a comment or a search box).
Common Validation Filters
These filters check the shape of the data and return false when it does not match.
| Filter | Checks For |
|---|---|
| FILTER_VALIDATE_EMAIL | A syntactically valid email address |
| FILTER_VALIDATE_INT | A whole number, optionally with min_range/max_range options |
| FILTER_VALIDATE_FLOAT | A floating-point number |
| FILTER_VALIDATE_URL | A syntactically valid URL |
| FILTER_VALIDATE_BOOLEAN | "1"/"true"/"on"/"yes" as true, "0"/"false"/"off"/"no"/"" as false |
<?php
var_dump(filter_var("42", FILTER_VALIDATE_INT));
var_dump(filter_var("not-a-number", FILTER_VALIDATE_INT));
var_dump(filter_var("https://example.com", FILTER_VALIDATE_URL));
var_dump(filter_var("javascript:alert(1)", FILTER_VALIDATE_URL));
// Restrict an integer to a specific range
$age = filter_var("15", FILTER_VALIDATE_INT, [
"options" => ["min_range" => 18, "max_range" => 120],
]);
var_dump($age); // false, because 15 is below min_rangeint(42)
bool(false)
string(19) "https://example.com"
bool(false)
bool(false)Common Sanitization Filters
Sanitization filters clean a string by removing or encoding characters, rather than rejecting it outright.
| Filter | Effect |
|---|---|
| FILTER_SANITIZE_SPECIAL_CHARS | HTML-encodes special characters like <, >, and & (the modern replacement for the deprecated FILTER_SANITIZE_STRING) |
| FILTER_SANITIZE_EMAIL | Removes characters that are illegal in an email address |
| FILTER_SANITIZE_NUMBER_INT | Removes everything except digits, +, and - |
| FILTER_SANITIZE_FULL_SPECIAL_CHARS | A more complete HTML-entity encoding, similar to htmlspecialchars() |
FILTER_SANITIZE_STRING was deprecated in PHP 8.1 and removed in PHP 9. Use FILTER_SANITIZE_SPECIAL_CHARS (or htmlspecialchars() directly) for new code instead.
<?php
$comment = "<b>Nice post!</b> 5 stars";
$safe = filter_var($comment, FILTER_SANITIZE_SPECIAL_CHARS);
echo $safe;<b>Nice post!</b> 5 starsExample: Validating a Form
Imagine a small signup form that submits an email address and an age. Before doing anything else with this data — like saving it to a database — you should validate both fields and collect any errors.
<?php
// Pretend this came from $_POST in a real form submission
$input = [
"email" => " jane@example.com",
"age" => "27",
];
$errors = [];
// Sanitize first (trim stray whitespace from copy/paste), then validate
$email = filter_var(trim($input["email"]), FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "Please enter a valid email address.";
}
$age = filter_var($input["age"], FILTER_VALIDATE_INT, [
"options" => ["min_range" => 13, "max_range" => 120],
]);
if ($age === false) {
$errors[] = "Age must be a whole number between 13 and 120.";
}
if (empty($errors)) {
echo "Form is valid! Email: $email, Age: $age";
} else {
echo "Please fix the following:\n";
foreach ($errors as $error) {
echo "- $error\n";
}
}Form is valid! Email: jane@example.com, Age: 27If the visitor had typed "not-an-email" and "9" instead, the same script would print both error messages, letting you re-show the form with helpful feedback rather than crashing or silently accepting bad data.
Common Mistakes
- Checking the result of filter_var() with if ($result) instead of if ($result !== false) — this misfires on values like "0".
- Relying only on sanitization and skipping validation for data that must be strictly correct, like an email or a numeric ID.
- Using the deprecated FILTER_SANITIZE_STRING in new PHP 8.1+ code.
- Forgetting that filter_var() only checks the shape of an email — it does not confirm the address actually exists or can receive mail.
Best Practices
- Validate any data whose format matters (emails, IDs, ages) before using it.
- Sanitize free-form text that will be displayed back to users, to prevent HTML/JS injection.
- Always compare validation results with the strict !== false check.
- Combine filter_var() with min_range/max_range options to enforce sensible business rules, like a minimum age.
- Never treat filtering as a replacement for prepared statements when working with SQL — they solve different problems.
Frequently Asked Questions
Does filter_var() protect against SQL injection?
Not by itself. Filtering cleans up general data shape, but you should still use prepared statements for any data that goes into a SQL query.
What does filter_var() return when validation fails?
It returns the boolean false, which is why you must check with the strict !== false comparison rather than a loose truthy check.
Can I filter an entire array of inputs at once?
Yes — filter_var_array() applies a set of filters to an array of values in one call, which is convenient for whole forms.
Is FILTER_VALIDATE_EMAIL enough to guarantee an email is real?
No, it only checks that the address is syntactically valid. To confirm it is real and reachable, you typically send a confirmation email.
Key Takeaways
- filter_var() validates or sanitizes a single value using a named filter constant.
- Validation checks whether data is well-formed and returns false if it is not.
- Sanitization cleans data by removing or encoding parts of it, and never returns false.
- FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_URL are common validation filters.
- FILTER_SANITIZE_SPECIAL_CHARS is the modern way to clean up free-form text for safe display.
Summary
PHP's filter extension gives you a reliable, built-in toolkit for handling untrusted input without hand-rolling checks yourself. filter_var() is the workhorse function, and knowing when to validate versus when to sanitize is the key skill this lesson covered.
Next, you will build on this by learning regular expressions, which give you much finer control over matching and manipulating text patterns than the built-in filters alone.
- You can validate emails, integers, and URLs with filter_var().
- You understand the difference between validating and sanitizing.
- You know the common sanitization filters and why FILTER_SANITIZE_STRING is deprecated.
- You built a small form validator combining multiple filters.