Filters in PHP are highly useful to filter and validate data coming from non reliable and insecure sources. Additionally, the PHP filter extension is designed to make data filtering easier and quicker. Almost all web applications depend on external input. Usually this comes from a user or another application (like a web service). Implementation of filters can stop the undesirable data. This external data can be in the form of cookies, web services, server variables and database query results etc. Some of the important functions in PHP which are used for this purpose would be discussed in this tutorial.
As an initial example, the filter_var() function can validate an integer. For example:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $int = 123; if(!filter_var($int, FILTER_VALIDATE_INT)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?> |
In the above example, the “FILTER_VALIDATE_INT” is used to filter the variable. Since the integer is valid, the output of the code above will be: “Integer is valid”. If we try with a variable that is not an integer (like “123abc”), the output will be: “Integer is not valid”.
For additional filtering features, options and flags can be utilized. Different filters have different options and flags. In the example below, we validate an integer using the filter_var() and the “min_range” and “max_range” options:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $var=300; $int_options = array( "options"=>array ( "min_range"=>0, "max_range"=>256 ) ); if(!filter_var($var, FILTER_VALIDATE_INT, $int_options)) { echo("Integer is not valid"); } else { echo("Integer is valid"); } ?> |
Options must be put in an associative array with the name “options”. If a flag is used it does not need to be in an array.
In the example below, we would validate an input coming from a form. For that, before validating the data, its existence would be confirmed. Then it would be filtered using the filter_input () function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php if(!filter_has_var(INPUT_GET, "email")) { echo("Input type does not exist"); } else { if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) { echo "Email is not valid"; } else { echo "Email is valid"; } } ?> |
The above example would check if an “email” input variable of the “GET” type exist. After that, it would check if it is a valid email address.
With the utilization of filters, users can get rid of the annoying and unwanted data that keep pouring from random resources. This can also be implemented to get rid of spamming.