← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 6 of 8

PHP Filters

What is filter_var()?

filter_var() validates or sanitizes a single value against a named filter in one function call, returning the cleaned value on success or false on failure. It centralizes validation logic that would otherwise be scattered across regular expressions and manual checks.

Example: What is filter_var()?

php
<?php
$email = "[email protected]";
$result = filter_var($email, FILTER_VALIDATE_EMAIL);
echo $result;
?>

Validating Email and Integers

FILTER_VALIDATE_EMAIL checks a string against the structural rules of a valid email address, and FILTER_VALIDATE_INT confirms a value is a genuine integer — both return false on failure rather than throwing, so the result must always be checked with === false, not just falsy checks.

Example: Validating Email and Integers

php
<?php
var_dump(filter_var("[email protected]", FILTER_VALIDATE_EMAIL) === false);
var_dump(filter_var("42", FILTER_VALIDATE_INT) === false);
?>

Validating URLs and Booleans

FILTER_VALIDATE_URL confirms a string is a well-formed URL, while FILTER_VALIDATE_BOOLEAN interprets common truthy/falsy strings like "yes", "1", and "off" into a real boolean value, which is more forgiving than a plain PHP boolean cast.

Example: Validating URLs and Booleans

php
<?php
var_dump(filter_var("https://example.com", FILTER_VALIDATE_URL));
var_dump(filter_var("yes", FILTER_VALIDATE_BOOLEAN));
?>

Sanitizing Input

Sanitizing filters like FILTER_SANITIZE_STRING (or its modern replacement using htmlspecialchars) and FILTER_SANITIZE_EMAIL strip or encode unwanted characters from a value rather than rejecting it outright — useful when you want to clean input for safe display, not just verify its shape.

Example: Sanitizing Input

php
<?php
$comment = "<b>Hello</b>";
echo htmlspecialchars($comment) . "\n";
echo filter_var("user@ example.com", FILTER_SANITIZE_EMAIL);
?>

Why Filtering Matters for Untrusted Input

Any data coming from $_GET, $_POST, or $_COOKIE should be treated as untrusted until proven otherwise, since a user (or an attacker) fully controls what's sent. Filtering at the point of entry catches malformed or malicious data before it ever reaches a database query or gets echoed back into HTML.

Example: Why Filtering Matters for Untrusted Input

php
<?php
$_GET['id'] = "5 OR 1=1";
$id = filter_var($_GET['id'], FILTER_VALIDATE_INT);
var_dump($id);
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.