Hello! Welcome to the next lesson in your PHP mastery journey.
In our last lesson, we focused on handling internal application errors, specifically how to manage database issues using PDO exceptions. We learned to build robust code that can gracefully handle problems on the "inside."
Today, we shift our focus to the "outside"—the data that comes into your application from users. Your interest in cybersecurity makes this topic particularly relevant. In web development, a fundamental security principle is "never trust user input." Every piece of data from a form, a URL, or an API call must be treated as potentially unsafe until proven otherwise.
This lesson introduces the first line of defense: input validation. Your learning outcome is to be able to validate user input data types and formats using the filter_var() function. This is a critical skill for preventing bugs and blocking a wide range of security vulnerabilities.
1. The Twin Pillars of Input Handling: Validation and Sanitization
Before we write any code, it's crucial to understand two related but distinct concepts: validation and sanitization.
- Validation: This is the process of checking if a piece of data conforms to a set of rules. It answers a "yes or no" question. For example: "Is this a validly formatted email address?" or "Is this value an integer?". If the data fails validation, it is rejected.
- Sanitization: This is the process of cleaning data by removing or modifying illegal or unsafe characters. It doesn't reject the data; it changes it to make it safe. For example, stripping HTML tags from a user's comment to prevent them from injecting code.
Think of it like this:
- Validation is a security guard checking your ID to see if you're on the guest list. If not, you're denied entry.
- Sanitization is the same guard asking you to wipe your muddy shoes before you walk on the clean floor. You're still allowed in, but only after you're "cleaned up."
The following video provides a great introduction to why this is so important, especially for preventing malicious attacks.
PHP how to sanitize/validate input
The video 'PHP how to sanitize/validate input' from Bro Code gives a clear, practical demonstration of why we can't trust user input. It shows how a simple form can be exploited with a JavaScript injection.
Watch the first part of the video, from the beginning to 01:39. Pay close attention to how easily a malicious script can be executed when input is not handled correctly.
2. Your Primary Tool: filter_var()
PHP provides a powerful set of "filter" functions designed specifically for this purpose. Our focus today is on the most versatile one: filter_var().
As the official PHP manual explains, filter_var() filters a variable with a specified filter.
Let's look at the official PHP documentation for filter_var(). This will give us the formal definition and parameters.
Read the 'Description', 'Parameters', and 'Return Values' sections. Don't worry about memorizing everything; just focus on understanding the three main parts of the function call: the value, the filter, and the optional options.
The basic syntax is filter_var($value, $filter, $options).
$value: The variable you want to check (e.g.,$_POST['email']).$filter: A constant that specifies the validation rule to apply (e.g.,FILTER_VALIDATE_EMAIL).$options: An optional array or flags to add more specific rules.
When a validation filter is used, filter_var() returns the validated data if successful, and false if the validation fails. This makes it perfect for use in an if statement.
Common Validation Filters
Here are some of the most common validation filters you'll use:
| Filter Constant | Purpose |
|---|---|
FILTER_VALIDATE_EMAIL |
Checks if the value is a valid email address. |
FILTER_VALIDATE_INT |
Checks if the value is an integer. |
FILTER_VALIDATE_FLOAT |
Checks if the value is a floating-point number. |
FILTER_VALIDATE_URL |
Checks if the value is a valid URL. |
FILTER_VALIDATE_IP |
Checks if the value is a valid IP address. |
FILTER_VALIDATE_BOOLEAN |
Checks if the value is a boolean (true/false). |
This image provides a quick visual summary of how these are used in code.

3. A Practical Workflow for Form Validation
Let's put this into a real-world context. Imagine you have a form with an email field. How do you use filter_var() to handle the submission?
The most robust workflow often involves sanitizing first, then validating. This ensures you are validating the cleanest possible version of the input.

Here’s the process in code:
- Check if the form has been submitted (e.g., using
$_SERVER['REQUEST_METHOD'] == 'POST'). - Get the raw data from the
$_POSTsuperglobal. - Sanitize the input to remove any harmful or unnecessary characters. For an email,
FILTER_SANITIZE_EMAILremoves characters that are not allowed in emails. - Validate the sanitized data using
FILTER_VALIDATE_EMAIL. - If validation passes, use the data. If it fails, prepare an error message for the user.
The following video demonstrates this exact workflow. While it uses a related function, filter_input(), the logic is identical. filter_input(INPUT_POST, 'data', ...) is just a shortcut for filter_var($_POST['data'], ...).
PHP Front To Back [Part 14] - Filters & Validation
The video 'PHP Front To Back [Part 14] - Filters & Validation' by Traversy Media provides an excellent walkthrough of sanitizing and then validating form input.
Watch the segment from 05:36 to 08:45. Notice how the code first retrieves the raw post data, then uses filter_var with FILTER_SANITIZE_EMAIL to clean it, and finally uses filter_var again with FILTER_VALIDATE_EMAIL on the cleaned variable.
Here is a complete example you can study and run:
<?php
// Initialize variables to hold form data and errors
$email = '';
$errors = [];
// Check if the form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 1. Get raw data from the form field named 'email'
$raw_email = $_POST['email'] ?? '';
// 2. Sanitize the email to remove illegal characters
$sanitized_email = filter_var($raw_email, FILTER_SANITIZE_EMAIL);
// 3. Validate the sanitized email
if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) {
// If valid, store the clean email
$email = $sanitized_email;
// Proceed with application logic, e.g., save to database
} else {
// If invalid, add an error message to our errors array
$errors['email'] = 'Please enter a valid email address.';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Email Validation</title>
</head>
<body>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($errors)): ?>
<p>Thank you! Your email "<?= htmlspecialchars($email) ?>" has been validated.</p>
<?php else: ?>
<form action="" method="post">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<?php if (isset($errors['email'])): ?>
<span style="color: red;"><?= $errors['email'] ?></span>
<?php endif; ?>
<button type="submit">Submit</button>
</form>
<?php endif; ?>
</body>
</html>
4. Customizing Validation with Options
filter_var() can be made even more powerful by using its third parameter, $options. This allows you to add specific constraints to a validation filter.
For example, when validating an integer with FILTER_VALIDATE_INT, you can specify a minimum and maximum allowed value.
<?php
$number = '50';
$options = [
'options' => [
'min_range' => 1,
'max_range' => 100
]
];
if (filter_var($number, FILTER_VALIDATE_INT, $options)) {
echo "The number $number is between 1 and 100.";
} else {
echo "The number $number is NOT between 1 and 100.";
}
// Output: The number 50 is between 1 and 100.
?>
This is extremely useful for things like validating an age, a quantity, or a product ID. You can see more examples of options and flags in the filter_var() documentation and in the later parts of the Traversy Media video. For now, it's enough to know that this capability exists for when you need more fine-grained control.
Conclusion
You have now learned the fundamental skill of input validation in PHP. By treating all user data as untrusted and systematically checking it, you are building a solid foundation for secure and reliable web applications.
Key Takeaways:
- Always validate user input as a primary security measure.
- Validation confirms if data meets rules, while Sanitization cleans data by removing harmful characters.
- The
filter_var()function is your main tool for validating data against predefined filters likeFILTER_VALIDATE_EMAILandFILTER_VALIDATE_INT. - A robust pattern is to sanitize input first, and then validate the cleaned result.
- If validation fails, you should reject the input and provide clear feedback to the user.
Preview of the Next Lesson:
Today, we secured the front door by validating incoming data. But what happens when we need to display that data back to the user? If we're not careful, even validated data can be used for attacks. In the next lesson, we will address this by learning how to sanitize output by escaping HTML to prevent Cross-Site Scripting (XSS) attacks.