PHP filter_var: Understand How to Sanitize Input

PHP filter_var function

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used regular expressions. That leads to bugs and security issues. That’s why filter_var came in PHP.

In this article, you will understand how it works and cover the syntax. You will also see examples and use cases. Let’s get started.

Understand the filter_var() Function in PHP

filter_var() is a PHP function used to filter a variable. It can either validate the data (check if it meets certain criteria) or sanitize it (remove unwanted characters). It helps you to make sure the user input is clean and safe.

Here is the syntax:

filter_var($value, $filter, $options )
  • $value: The data to be filtered.
  • $filter: The type of filter. Can be a validation filter (FILTER_VALIDATE_*), sanitization filter (FILTER_SANITIZE_*), or a custom filter (FILTER_CALLBACK).
  • $options: An optional array or bitmask of flags to modify the behavior of the filter.

So, why use it over manual validation?

You can use it to handle inputs rather than using the manual methods. Here are the reasons for usage:

  • It provides a set of well-tested filters for common validation needs.
  • It helps you to prevent security issues, like SQL injections or XSS, by sanitizing input automatically.

Let’s move on to the following section to see the common case of the filter_var function.

Examples and Common Cases

It checks if a string is a valid email address. It detects the general structure of the email and is it includes the “@” symbol and domain.

For example:

$email = '[email protected]';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email!";
}

The function checks if $email matches the format of a typical email address “[email protected]”.

You can also check if a string is a valid URL with FILTER_VALIDATE_URL. It checks for proper structure and includes the scheme (http://, https://, etc.) and domain.

Here is an example:

$url = 'https://flatcoding.com';
if (filter_var($url, FILTER_VALIDATE_URL)) {
    echo "Valid URL!";
}

It verifies that the input is a correctly formatted URL before using it in an application, like linking to external websites.

Use FILTER_SANITIZE_STRING to remove unwanted characters, such as HTML or JavaScript tags, from a string.

Note: As of PHP 8.1.0, FILTER_SANITIZE_STRING is deprecated, but it’s still used in some legacy code.

For example:

$dirty_string = '<script>alert("hack")</script>';
$clean_string = filter_var($dirty_string, FILTER_SANITIZE_STRING);
echo $clean_string; 

The function strips HTML tags and potentially harmful content from $dirty_string. It leaves behind only plain text.

You can use also the FILTER_VALIDATE_INT to check if a string is a valid integer. You can also specify a range of acceptable values when you use the options array.

For example:

$number = '25';
$options = [
    'options' => ['min_range' => 10, 'max_range' => 100]
];
if (filter_var($number, FILTER_VALIDATE_INT, $options)) {
    echo "Valid number!";
}

It makes sure that user input is a valid integer and within an acceptable range.

Wrapping Up

In this tutorial, you learned how filter_var() in PHP helps you to handle user input. You understood its syntax and use cases such as:

  • Email validation.
  • URLs.
  • Strings sanitization.
  • Integers validation.

Here is a quick recap:

  • filter_var() is used to either validate or sanitize data. It makes sure the input meets specified criteria or removes unwanted characters.
  • It offers well-tested filters and input validation. It also helps you to protect against security threats like XSS or SQL injection.

Thank you for reading. To see more PHP tutorials, click here.

What is the purpose of the filter_var() function in PHP?

The filter_var() function in PHP is used to filter a variable by either validating or sanitizing it. Validation ensures that the data meets specific criteria (e.g., a valid email address), while sanitization removes unwanted characters to make the data safe for use. This function helps in ensuring that user input is clean and secure, preventing potential security issues like SQL injections or XSS attacks.​

How do you validate an email address using filter_var()?

To validate an email address, you can use the FILTER_VALIDATE_EMAIL filter with filter_var(). Here's an example:​
$email = '[email protected]';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email!";
}
This code checks if the $email variable contains a valid email address format. If it does, it outputs "Valid email!".
Previous Article

PHP filter_id Function: How to Retrieve PHP Filter IDs

Next Article

filter_has_var Function: Check if Input Exists in PHP

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.