Php Filters: The Best Way to Sanitize and Validate Datas

What are PHP filters, PHP filter_var() function, sanitize form input, PHP callback function & array filter

by admin admin Date: 02-03-2020 php filters

What are PHP filters?

One of the most amazing strengths of PHP is its convenience. Shockingly this same profit has worked against PHP as numerous new coders have forgotten any security to establish safety or fails to offer the adroitness to make a class to validate their variables from end users.

One of the most fabulous strengths of PHP is its convenience. Unfortunately this same profit has worked against PHP as numerous new coders have forgotten any security measures or fails to offer the expertise to make a class to validate their variables from closure clients.

The PHP filter extension has a large number of the functions required for checking numerous sorts of client input. Took care of by provides a standard strategy for filtering data. You might as well dependably filter all external data!

What is external data?

  • Input data from a form
  • Cookies
  • Web services data
  • Server variables
  • Database query results

Getting started with PHP filter

To get a look at what the filter extension has to offer, we can easily list all the available PHP filters with the PHP filter_list() function.

Example on PHP filter:

<tr><td>Filter Name</td><td>Filter ID</td></tr>
foreach(filter_list() as $id =>$filter)
 echo '<tr><td>'.$filter.'</td><td>'.filter_id($filter).'</td></tr>'."n";

Output will be:

Filter Name Filter ID
int 257
boolean 258
float 259
validate_regexp 272
validate_url 273
validate_email 274
validate_ip 275
string 513
stripped 513
encoded 514
special_chars 515
unsafe_raw 516
email 517
url 518
number_int 519
number_float 520
magic_quotes 521
callback 1024

This is quite an impressive list and more will be added in time. Note also that each filter has its own Filter ID, this will become useful as we progress through this tutorial.

Each of these filters can be used with the PHP filter_var() function and here we will step through each one show how it works. Note that the string and stripped have the same ID. This is because they are the same.

Functions to filter a variable Using following function we can filter a variable:

  • PHP filter_var() - Filters a single variable with a specified filter
  • PHP filter_var_array() - Filter several variables with the same or different filters
  • PHP filter_input - Get one input variable and filter it
  • PHP filter_input_array - Get several input variables and filter them with the same or different filter.

PHP Filtering a variable

The actual filtering of variables is done with the PHP filter_var() function.

Let’s start with a simple integer filter to see how it works.

/*** an integer to check ***/ 
$int = 'abc1234'; 
/*** validate the integer ***/ 
echo filter_var($int, FILTER_VALIDATE_INT); 

Now we see a different result. No display is made because the variable $int has failed validation and the filter_var() function has returned bool(false).

Also note that if the variable is set to $int='' then it will again return bool(false).

The Input PHP Filter

As the name recommends, the input filter gets input from outside our script and can then filter it. The function utilized for this is the PHP filter_input() function.

With this we can validate our variables as they come in from user side and be sure they are dealt with before we start using them.

The input filter can gather data from several sources.

  • INPUT_SESSION (Not yet implemented)
  • INPUT_REQUEST (Not yet implemented)

Here follows a simple example of using the PHP filter_input() function to deal with GET variables.
Let’s assume you have a URL of the type
Let’s see how we can validate this using our input filter.

/*** filter the input number from GET ***/ 
if(filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT, 
array("options" => array("min_range"=>1, "max_range"=>10))) != FALSE) 
 echo $_GET['num'].' is valid';
 echo 'Invalid number supplied'; 

As viewed with previous utilization of the FILTER_VALIDATE_INT PHP filter, we are ready to validate that the supplied quality is a digit and that it is with the reach of 1 to 10. Might as well an invalid quality be supplied the PHP filter_input will give return bool(false).

The INPUT_GET parameter tells the PHP filter_input that the value is coming from GET.

PHP Sanitize Input

It is well to be able to validate the data we use. It is equally important to be able to clean up any data that may come to our scripts, especially data from user land.

The PHP filter_var() function also contains filters for many data types that will clean up data for use in our scripts.

Here we will show their uses in a simple context.
Here is the example of sanitizing url:
The PHP FILTER_SANITIZE_URL will strip out illegal characters. The characters that are not removed are
letters and digits and the following: $ - _ . + ! * ' ( ) , { } | ^ ~ [ ] ` > < # % " ; / ? : @ & = .

if(!filter_has_var(INPUT_POST, "url"))
echo("Input type does not exist"); 
/*** sanitize the input URL ***/ 
$url=filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL);

First 'if' checks the existence of the input data. If the input variable exists, sanitize (take away invalid characters) and store it in the $url variable.

And in the above script if input is http://www.goååogølø, the $url will be :

PHP Filter Multiple Inputs

Filtering multiple variables goes along the same lines as the filtering single variables.

There are two functions that are used to deal with multiple variables:

  1. PHP filter_input_array
  2. PHP filter_var_array

The filter_input_array function takes the following arguments:

  1. type - refers to the superglobal array that you intend to use, i.e. $_GET
  2. definition - refers to a array that defines the arguments. In this case it's a multidimensional array that determines how the variables are to be filtered.

The filter_var_array function takes the following arguments:

  1. data - refers to an array containing the variables that you want to filter
  2. definition- same as filter_input_array function.

Example of PHP filter multiple inputs:

error_reporting(E_ALL | E_STRICT); 

/* data actually came from POST 
$_POST = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',

$args = array (
               'product_id' => FILTER_SANITIZE_ENCODED,
               'component' => array(
                                       'filter' => FILTER_VALIDATE_INT,
                                          'flags' => FILTER_FLAG_ARRAY, 
                                       'options' => array(
                                                             'min_range' => 1, 
                                                             'max_range' => 10
               'versions' => FILTER_SANITIZE_ENCODED,
               'doesnotexist' => FILTER_VALIDATE_INT,
               'testscalar' => array(
                                        'filter' => FILTER_VALIDATE_INT,
                                        'flags' => FILTER_FLAG_SCALAR,
               'testarray' => array(
                                       'filter' => FILTER_VALIDATE_INT,
                                       'flags' => FILTER_FLAG_ARRAY,

$myinputs = filter_input_array(INPUT_POST, $args);
echo "n";

Output will be:

array(6) {
          array(1) {
                    string(17) "libgd%3Cscript%3E"
          array(1) {
          array(1) {
                    string(6) "2.0.33"
          array(1) {

Using Callback Filter

The FILTER_CALLBACK filter does precisely what it states. Calls a user defined function  to filter our data.

This usefulness licenses us full control of the filtering of data. Here we will start with a straightforward client demarcated function that changes over spaces to underscores.

* Callback function
* Convert spaces to underscores
* @param $string
* @return string

function space2underscore($string) 
 return str_replace(" ", "_", $string);

$string = "This is not a love song";
echo filter_var($string, FILTER_CALLBACK, array("options"=>"space2underscore"));

We see the filter has used our space2underscore() function as a callback and converted the spaces in the string so that it now returns

Output will be:

by admin admin Date: 02-03-2020 php filters hits : 20899  

Related Posts