Quick Guide To PHP Filters

PHP filters are used for validating and sanitizing user input. PHP filters help web developers ensure that input from users is safe and meets certain requirements, such as a valid email address, a numeric value, or a specific format.

In this article, we’ll discuss what PHP filters are, how they work, and how to use them effectively in your PHP code.



What are PHP Filters?

PHP filters are built-in functions that can be used to validate and sanitize user input. The purpose of filters is to ensure that data entered by users is safe and conforms to certain standards.

PHP filters provide a simple and effective way to validate and sanitize user input, which is essential for security and usability of web applications.

There are plenty of PHP filter functions available that can be used to validate and sanitize data in a quick and efficient manner.

Filters can be classified into two main categories validation filters and sanitization filters.


Why Use Filters?

There are many web applications that receive input from external sources. Input/data can be:

  • Input from a form provided by the user.
  • Cookie information.
  • Data from web services.
  • Variables on the server.
  • Results of a database query.
  • Validate external data always!
Submitted data that is not valid can lead to security issues on your website and even break it.

When you use PHP filters, you can ensure the input to your application is correct and you don’t have to worry about it!


PHP Filter Extension

As part of the validation and sanitization of external input, PHP filters are used.

PHP filter extension has many functions that are required to verify user input and is designed to simplify and speed up the process of data validation for PHP programs.

Before using PHP filters, it is essential to specify the filter type, such as validation or sanitization. Additionally, you should provide the input data you wish to filter along with any necessary options or parameters required by the filter.

This function, filter_list(), can be used to list the features that the PHP filter extension offers, like:

Example: 

<table> <tr> <td>Filter Name</td> <td>Filter ID</td> </tr> <?php foreach (filter_list() as $id => $filter) { echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>'; } ?> </table>

PHP filter_var() Function

Using the filter_var() function, you can verify and sanitize data. A single variable can be filtered by the filter_var() function using the specified filter.

There are two pieces of information that are required:

  • Variables to check.
  • Check type to be used in the assessment.

String Sanitization

A sanitization process involves the removal of characters from foreign input that are illegal or unsafe.

The following example shows how to remove all HTML tags from a string by using the filter_var() function:

Example: 

<?php $string = "<h1>Hello, from mrexamples</h1>"; $sanitize_str = filter_var($string, FILTER_SANITIZE_STRING); echo $string; //without sanitize echo $sanitize_str; //after sanitize ?>

Validate an Integer

Here is an example of how to check whether the variable $number is an integer by using the filter_var() function.
If the variable $number is a valid integer, then the output of the code below will be as follows: “Variable is a valid integer.” However, if $number is not a valid integer, then the output will be: “Variable is not a valid integer“:

Example: 

<?php $number = 88; if (!filter_var($number, FILTER_VALIDATE_INT) === false) { echo("Variable $number is a valid integer"); } else { echo("Variable $number is not a valid integer"); } ?>
Note: if $number was set to 0, the function above would return the message “Variable is not a valid integer“.
You can solve this problem by using the following code:

Example: 

<?php $number = 0; if (filter_var($number, FILTER_VALIDATE_INT) === 0 || !filter_var($number, FILTER_VALIDATE_INT) === false) { echo("Variable $number is a valid integer"); } else { echo("Variable $number is not a valid integer"); } ?>

The example below shows how you can use the filter_var() function and the FILTER_VALIDATE_INT filter in PHP to validate an integer within a range.

The options parameter allows you to specify the range for the integer to be validated.

Example: 

<?php $num = 122; $min_range = 1; $max_range = 200; if (filter_var($num, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min_range, "max_range"=>$max_range))) === false) { echo("$num is not in the range"); } else { echo("$num is in the range"); } ?>

Here, let’s take an example of validating the age of adults from 18 to 60 using the filter_var() function:

Example: 

<?php $age = 23; $options = array('options' => array( 'min_range' => 18, 'max_range' => 60) );if (filter_var($age, FILTER_VALIDATE_INT, $options) === false) { echo "Age is not valid"; } else { echo "Age is valid"; } ?>

IP Address Validation

To check whether $ip_add is a valid IP address, we use the filter_var() function to perform the following check:

Example: 

<?php $ip_add = "192.168.0.1"; if (!filter_var($ip_add, FILTER_VALIDATE_IP) === false) { echo("$ip_add : is valid IP address"); } else { echo("$ip_add : is valid IP address"); } ?>

Validate IPv6 Address

The filter_var() function can be used to validate an IPv6 address by setting the FILTER_VALIDATE_IP filter and also specifying the flags parameter, which indicates that the IPv6 address should be validated, and the following is an example of how to validate an IPv6 address using PHP:

Example: 

<?php $ip_v6 = "1ba9:b612:11fc:4d95:5b11:468a:1e4d:3467"; if (!filter_var($ip_v6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { echo("$ip_v6 is a valid IPv6 address"); } else { echo("$ip_v6 is not a valid IPv6 address"); } ?>
In this example we are going to validate IPv6 address while the variable stores IPv4 address:

Example: 

<?php $ip_v6="127.0.0.0"; if (!filter_var($ip_v6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) { echo("$ip_v6 is a valid IPv6 address"); } else { echo("$ip_v6 is not a valid IPv6 address"); } ?>

Email Address: Validate & Sanitize

To validate email address, we will use the filter_var() function to first remove all illegal characters from the $email_add variable, and then we will check if the email address is valid using the following syntax:

Example: 

<?php $email_add = "[email protected]"; $email_add = filter_var($email_add, FILTER_SANITIZE_EMAIL); // Remove all illegal characters // Validating e-mail if (!filter_var($email_add, FILTER_VALIDATE_EMAIL) === false) { echo("$email_add : valid email address"); } else { echo("$email_add : not valid email address"); } ?>

URL Validation and Sanitization

In the following example, we use the filter_var() function in order to first remove all illegal characters from a URL, and then determine whether $url is a valid URL based on the removed characters:

Example: 

<?php $url = "https://mrexamples.com"; $url = filter_var($url, FILTER_SANITIZE_URL);// Remove all illegal characters from a url // Validating url if (!filter_var($url, FILTER_VALIDATE_URL) === false) { echo("$url :is a valid URL"); } else { echo("$url :is not a valid URL"); } ?>

Validate Query String URLs

You can validate a URL containing a query string in PHP by using the filter_var() function with the FILTER_VALIDATE_URL filter, and then using the parse_url() filter to check if it contains a query string. Here is an example of how you can validate an URL in PHP through the filter_var() function:

Example: 

<?php $url = "https://mrexamples.com/php?query=filter"; if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) { echo("$url is a valid URL containing a query string"); } else { echo("$url is not a valid URL containing a query string"); } ?>
In this example, we are now going to check the output of the URL without the use of a query string:

Example: 

<?php $url = "https://mrexamples.com/php"; //filtering URL with query string if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) { echo("$url is a valid URL containing a query string"); } else { echo("$url is not a valid URL containing a query string"); } ?>

Remove ASCII Characters

This example illustrates how to sanitize a string by using the filter_var() function.

All HTML tags in the string, as well as all characters with ASCII values > 127, will be removed by this function:

Example: 

<?php $string = "<h1>PHP is Fun!!ÆØö…!</h1>"; $new_string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); echo $new_string; ?>
Here, we are taking another string to validate and remove ASCII characters whose values are more than 127:

Example: 

<?php $string="Mr examples <is> 🅖🅡ⓔⓐ🅣 place for learning "; $new_string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); //eliminates <is> and 🅖🅡ⓔⓐ🅣 echo $new_string; ?>

Benefits Of PHP Filters

PHP filters provide significant benefits for web application development by enhancing security, improving data quality, saving time and costs, improving user experience, and providing flexibility and customizability.

  • PHP filters help prevent security vulnerabilities such as SQL injection and cross-site scripting (XSS) attacks by validating and sanitizing user input. This significantly reduces the risk of data breaches and unauthorized access to sensitive information.
  • By validating user input against a set of rules, PHP filters help ensure that data entered by users is accurate and meets specific standards. This results in better data quality, which can improve the overall functionality and usability of web applications.
  • It can save your time and money by reducing the need for manual input validation and sanitization. With PHP filters, you can easily implement a standard set of rules to validate and sanitize user input, which can save time and reduce development costs.
  • You can ensure that user input is formatted and validated correctly, providing a better user experience for users. This can increase user satisfaction and retention, leading to better business outcomes.
  • It provides a flexible and customizable way to validate and sanitize user input. You and other web developers can customize filters to meet specific requirements and can easily modify and extend them as needed.
We value your feedback.
+1
0
+1
0
+1
1
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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