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 = 'username@emailservice.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email!";
}

The function checks if $email matches the format of a typical email address “username@emailservice.com”.

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 = 'user@example.com';
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!".

Similar Reads

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

Abstract Class in PHP: How It Works & Examples

Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…

PHP rtrim Function: Remove Trailing Characters or Whitespace

You deal with user input, file reads, or formatted strings. PHP needed a way to remove extra characters from the…

PHP array_merge_recursive: Merge Arrays Deeply

PHP array_merge_recursive joins two or more arrays into one nested array and keeps all values with their keys. Syntax of…

PHP break Statement: How to Exit a Loop

The PHP break statement helps in controlling the flow of loop work. It gives you a way to stop a…

PHP array_combine: How to Merge Arrays as Key and Value

The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

PHP XML Parsers: Everything You Need to Know

In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

PHP XML Expat Parser: A Complete Guide

If you've ever tried to pull data from an XML file, you know it can be a bit tricky at…

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.