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 Janeth Kent 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:

<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>'."n";
}
?>
</table>

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_GET
  • INPUT_POST
  • INPUT_COOKIE
  • INPUT_ENV
  • INPUT_SERVER
  • 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 http://www.example.com?num=7
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';
} 
else 
{ 
 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"); 
} 
else 
{ 
/*** 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øe.com/, the $url will be :
http://www.google.com/

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);
var_dump($myinputs);
echo "n";


Output will be:

array(6) {
        ["product_id"]=>
          array(1) {
                  [0]=>
                    string(17) "libgd%3Cscript%3E"
               }
        ["component"]=>
          array(1) {
                  [0]=>
                    int(10)
               }
        ["versions"]=>
          array(1) {
                  [0]=>
                    string(6) "2.0.33"
               }
        ["doesnotexist"]=>
          NULL
        ["testscalar"]=>
          bool(false)
        ["testarray"]=>
          array(1) {
                  [0]=>
                    int(2)
               }
         }

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:

This_is_not_a_love_song.
 
by Janeth Kent Date: 02-03-2020 php filters hits : 32938  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The most popular Array Sorting Algorithms In PHP

There are many ways to sort an array in PHP, the easiest being to use the sort() function built into PHP. This sort function is quick but has it's limitations,…

MySQL 8.0 is now fully supported in PHP 7.4

MySQL and PHP is a love story that started long time ago. However the love story with MySQL 8.0 was a bit slower to start… but don’t worry it rules…

A roadmap to becoming a web developer in 2019

There are plenty of tutorials online, which won't cost you a cent. If you are sufficiently self-driven and interested, you have no difficulty training yourself. The point to learn coding…

10 PHP code snippets to work with dates

Here we have some set of Useful PHP Snippets, which are useful for PHP Developers. In this tutorial we'll show you the 10 PHP date snippets you can use on…

8 Free PHP Books to Read in Summer 2018

In this article, we've listed 8 free PHP books that can help you to learn new approaches to solving problems and keep your skill up to date.   Practical PHP Testing This book…

Best Websites to Learn Coding Online

You know and we know that it’s totally possible to learn to code for free... If you can teach yourself how to write code, you gain a competitive edge over your…

PHP and XMP format: Create a Panorama 360/VR viewer in PHP and A-Frame

The Extensible Metadata Platform (XMP) is an ISO standard, originally created by Adobe Systems Inc., for the creation, processing and interchange of standardized and custom metadata for digital documents and…

PHP: Basic Introduction to Namespaces

History of PHP Namespaces In PHP prior to 5.3 (2009), any class you define lived at the same global level as other classes. Class User, class Contact, class Db they're all together…

PHP 7.2 will be the first Programming Language to add Modern Cryptography to its Standard Library

Last week, the voting phase closed on an RFC to add libsodium to PHP 7.2. The result was unanimous (37 in favor, 0 against). When version 7.2 releases at the end…

Php: How to extend the highlight_string function

PHP has a cool function that automatically highlights PHP code called highlight_string(); Theoretically this could be used to roll your own code highlighting on a site, rather than rely on…

Install Apache, MariaDB and PHP7 on Ubuntu 16.04

Ubuntu 16.04 LTS Xenial Xerus comes with PHP7 by default so you don’t have to rely on third-party PPA to get PHP7 installed. In this tutorial, we are going to…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration