Skip to Content
Course content

102: filter_var for Input Validation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why should I use filter_var instead of just writing a regex?

I've seen plenty of developers spend hours crafting the "perfect" regular expression to validate an email address, only to find out that some perfectly valid email format breaks their code. Honestly, it's a rabbit hole you don't want to go down. PHP's filter_var() is essentially a wrapper around a set of proven, standardized validation rules. It's faster to write, easier for the next person on your team to read, and significantly less prone to the edge-case bugs that plague custom regex.

// The "hard" way (regex)
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) { 
    /* ... */ 
}

// The professional way
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "That looks like a real email.";
}

What is the actual difference between validating and sanitizing?

This is a common point of confusion. Think of validation as a gatekeeper: it asks "Is this input acceptable?" and returns a boolean (or the value if it's valid). If the input is bad, validation tells you to reject it entirely.

Sanitization, on the other hand, is like a filter. It doesn't tell you if the data is "right" or "wrong"; it just strips out the characters that shouldn't be there. I usually sanitize first to clean up accidental whitespace or illegal characters, and then validate to ensure the result is actually useful.

$input = " user@example.com "; // Note the leading/trailing spaces

// Sanitization: removes illegal characters from email
$clean_email = filter_var($input, FILTER_SANITIZE_EMAIL);

// Validation: checks if the cleaned string is actually a valid email format
if (filter_var($clean_email, FILTER_VALIDATE_EMAIL)) {
    echo "Clean and valid!";
}

Can I use this for things other than emails and URLs?

Absolutely. It's incredibly useful for numbers. For instance, if you're building a form where a user enters their age, you don't just want to know if it's an integer; you want to know if it's a reasonable integer. You can pass an options array to filter_var to define a specific range.

I use this all the time for pagination or age-restricted content. It saves me from writing a bunch of if ($age > 0 && $age < 120) statements.

$age = "25";

$options = [
    'options' => [
        'min_range' => 1,
        'max_range' => 120
    ]
];

if (filter_var($age, FILTER_VALIDATE_INT, $options)) {
    echo "Age is a valid integer within the human lifespan.";
} else {
    echo "Please enter a realistic age.";
}



📋 Practical Task

Exercise: Build a User Profile Submission Validator

Imagine you are building a registration page. Create a PHP script that processes a mock $_POST array containing the following fields: email, website, and experience_years.

  • Email: Sanitize the input first, then validate it.
  • Website: Validate that it is a properly formatted URL.
  • Experience Years: Validate that it is an integer between 0 and 50.

Your script should collect any validation errors into an array. If the array is empty, print "Profile is valid!"; otherwise, print a list of all the specific errors found.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.