Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The PHP Filter Extension
3.
PHP filter_var() Function
4.
Validating an Integer
5.
Sanitizing a String
6.
Validating an IP Address
7.
Sanitising and Validating an Email Address
8.
Sanitizing and Validating a URL
9.
PHP Filter Functions
10.
PHP Predefined Filter Constants
10.1.
Validate filter constants
10.2.
Sanitise filter constants
11.
FAQs
12.
Key Takeaways
Last Updated: Mar 27, 2024

PHP Filters

Author Ranjul Arumadi
2 upvotes

Introduction

Many web applications use external input. User input from a form, cookies, web services data, server variables, and database query results are all examples of external input/data. But what if part of this information is incorrect?

 

Invalid data might cause security issues and even cause your website to crash!. We don't want that ever to happen. We can use PHP filters to ensure that our application receives the correct input to solve this problem. PHP filters help us to validate and sanitize external input easily.

The PHP Filter Extension

PHP filter extensions are used to validate and sanitize external input. Many of the functions needed to verify user input are included in the PHP filter extension, making data validation easier and faster.

 

Filters can be divided into two categories:

Validation: It is performed to see if the data is in the correct format.

Sanitization: It removes any unlawful characters from the data. However, It does not validate the data.

PHP filter_var() Function

The filter_var() function validates and sanitises data.

 

The filter_var() function applies a filter on a single variable. It requires the two pieces of information:

  • The variable to check.
  • The type of check we want use

 

The following is the syntax for this function:

filter_var(variable, filter)
You can also try this code with Online PHP Compiler
Run Code

Validating an Integer

The filter_var() function is used in the following example to determine whether the variable $int is an integer. If $int is an integer, the following code will return "Valid Integer." The output will be "Not Valid Integer" if $int is not an integer.

 

Example:

<?php
$int = 50;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
 echo("Valid Integer");
} else {
 echo("Not Valid Integer");
}
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Sanitizing a String

The filter_var() function is used in the following example to remove all HTML tags from a string:

 

Example:

<?php
// Sample user comment
$string = "<h1>Hello Worlds! I am removing HTML tags.</h1>";

// Sanitise and print comment string
$sanitisedstring = filter_var($string, FILTER_SANITIZE_STRING);
echo $sanitisedstring;
?>
You can also try this code with Online PHP Compiler
Run Code

 

The output of the code will be a string without all these HTML tags.

Output:

Validating an IP Address

The filter_var() function is used in the following example to determine whether a variable is a legitimate IP address:

 

Example:

<?php
$ipAddress = "99920.0.0.1";

if (!filter_var($ipAddress, FILTER_VALIDATE_IP) === false) {
 echo("$ipAddress is a valid IP address");
} else {
 echo("$ipAddress is not a valid IP address");
}
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Sanitising and Validating an Email Address

The filter_var() function is used in the following example to remove all prohibited characters from the variable and then determines whether it is a valid email address:

 

Example:

<?php
$email = "@example.test@example.com";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
 echo("It is a valid email address");
} else {
 echo("It is not a valid email address");
}
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Sanitizing and Validating a URL

The filter_var() function is used in the following example to eliminate all prohibited characters from a URL before checking if $url is a valid URL:

 

Example:

<?php
$url = "https:/www.codingninjas.com";

// Remove all illegal characters from a URL

$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url

if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
 echo("Valid URL");
} else {
 echo("Not a valid URL");
}
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

PHP Filter Functions

PHP has several filter functions to filter the data coming from various sources.

Function

Description

filter_has_var() Checks for the existence of a variable of a particular input type.
filter_id() Returns the filter ID for a given filter name
filter_input() Gets an external variable (for example, through form input) and filters it if necessary.
filter_input_array() Gets external variables (for example, from form input) and filters them if necessary.
filter_list() Returns a list of all filter names that are supported.
filter_var() Filters a variable using a specified filter.
filter_var_array() Obtains several variables and filters them.

PHP Predefined Filter Constants

PHP has many predefined filter constants. Some of them are listed below.

Validate filter constants

These PHP filter constants are used to validate data.

Constants

Description

FILTER_VALIDATE_INT an integer is validated
FILTER_VALIDATE_FLOAT a float is validated
FILTER_VALIDATE_BOOLEAN a boolean is validated
FILTER_VALIDATE_REGEXP a regular expression is validated
FILTER_VALIDATE_IP an IP address is validated
FILTER_VALIDATE_EMAIL an email address ​​is validated
FILTER_VALIDATE_URL an URL is validated

Sanitise filter constants

These PHP filter constants are used to filter the data for any invalid characters.

Constants Description
FILTER_SANITIZE_EMAIL Prohibited characters are removed from an email address.
FILTER_SANITIZE_NUMBER_INT All characters except digits, +, and – are removed from a number.
FILTER_SANITIZE_NUMBER_FLOAT Remove all characters except digits, +, and - from a float number.
FILTER_SANITIZE_URL Prohibited characters are removed from the URL.
FILTER_SANITIZE_SPECIAL_CHARS Special characters are removed.
FILTER_SANITIZE_ENCODED Special characters are removed/encoded.
FILTER_SANITIZE_STRING Tags and special characters are removed from a string.
FILTER_SANITIZE_STRIPPED FILTER_SANITIZE_STRING's alias
FILTER_SANITIZE_MAGIC_QUOTES Use the function addslashes().

FAQs

  1. What are filters in PHP?
    External input is validated and sanitized using PHP filter extensions. The PHP filter extension includes many of the functions required for validating user input; it is designed to make data validation easier and faster.
     
  2. How many types of filters are present in PHP?
    There are two main types of filters in PHP: validation and sanitization.
    Validation is a process done to ensure that the data is in the right format.
    Sanitization is the process of removing any illegal characters from data. However, it does not validate the data.
     
  3. What does data sanitization mean in PHP?
    Data sanitization refers to the removal of any unlawful characters from the data. One of the most important tasks in a web application is sanitizing user input. PHP includes a native filter extension that you can use to sanitize the data to make this work easier.

Key Takeaways

Any website is subjected to various inputs from a variety of sources, making it critical for us to safeguard our website against potential threats. External data can be validated and sanitized using PHP filters extensions. Many predefined PHP filters constants exist, all of which are designed to make data validation easier and faster.

 

If you loved reading this article about PHP filters, check out Why Use PHP programming in 2021? Its Pros and Cons and 5 Best Free PHP Projects With Source Code To Work In 2021.

Live masterclass