Is there any advantage in using the filter_input function instead of isset?

24

I've always been used to using isset to check if an external variable is populated and if you're using it.

Example:

if(isset($_GET['pag']))
     $pag = $_GET['pag'];

Now I've installed NetBeans and give me a Warning to say to use the filter_input .

Example:

if($pag = filter_input(INPUT_GET , 'pag'));

Is there any advantage in using filter_input ?

    
asked by anonymous 10.10.2014 / 12:23

6 answers

13

As can be seen in the function documentation filter_input (English) :

  

filter_input - Gets a specific external variable by name and optionally filters it

What translated:

  

filter_input - Gets a specific external variable by name and optionally filters its value.

The advantage of using the filter_input function is that not only will we collect the value, but we can filter it as well:

$search_html = filter_input(INPUT_GET, 'chavePesquisa', FILTER_SANITIZE_SPECIAL_CHARS);

Useful to protect, clean or validate user data without using multiple functions and multiple lines of code.

The list of filters can be found here:

PHP Manual > Function Reference > Variable and Type Related Extensions > Filter (English)

    
10.10.2014 / 12:50
10

The main difference is that isset () checks if there is any value in the variable, while with filter_input () it is possible to do some validations or cleanups in the entries.

the list of validations and cleanups

The use of filter_input() can sometimes simplify validations, for example an age range, where a child would not pay a bus ticket, or would have a differential value in charging a meal at a restaurant.

Validation with filter_input :

$options = array('options' => array('min_range' => 0, 'max_range' => 6 ));
if($idade = filter_input(INPUT_GET, 'search', FILTER_VALIDATE_INT, $options)){
    echo 'isento de pagar a passagem de ônibus pois sua idade é: '. $idade;
}else{
    echo 'Na dúvida sempre cobre, idade: '. $idade;
}

A traditional form of validation:

$idade = -1;
if(isset($_GET['search']) && ctype_digit($_GET['search'])){
    $idade = $_GET['search'];
}

if($idade >= 0 && $idade <= 6){
    echo 'Isento de pagar a passagem de ônibus pois sua idade é: '. $idade;
}else{
    echo 'Na dúvida sempre cobre, idade: '. $idade;
}
    
10.10.2014 / 12:54
7

The advantage of using filter_input is in the ease of applying filters in your string .

The same result can be obtained with the function filter_var , which implements the constants of FILTER

The filter_input would have the same function as:

// Sem filter_input
$email = filter_var($_GET['email'], FILTER_VALIDATE_EMAIL);

// Usando filter input
$email = filter_input(INPUT_GET , 'email', FILTER_VALIDATE_EMAIL);

The filter_* functions are few used by beginners, but they are quite useful. In the above example for example, php already validates if input is an email, without having to resort to Regular Expressions monstras .

With a little creativity, using a cousin of the filter_input function, filter_input_array , we can validate our forms with a very expressive and elegant code.

Adapted example of documentation:

<?php

$data = 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_FORCE_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_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);

It results in the following array already treated:

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)
  }
}
    
10.10.2014 / 12:52
5

Yes, and a lot of advantage, since with it you do the "cleaning" of the input data when using the third parameter, which is filter type . There are several filters that you can substitute for the manual validations you were accustomed to doing, such as validating an email address or simply checking if an entry is a number.

Some examples:

if ($email = filter_input(INPUT_POST , 'email', FILTER_VALIDATE_EMAIL)) {
    // é um e-mail válido
}

if ($numero = filter_input(INPUT_POST , 'numero', FILTER_VALIDATE_INT)) {
    // é um inteiro
}

The filters, as you can check in the URL above, can be both for validation and for "sanitizing" an input data.

Remembering that it is available from the 5.2.0 version.

    
10.10.2014 / 12:50
5

Something I think no one has commented on, but I think it's important to note that filter_input has a big difference compared to isset .

The isset will check whether a particular one exists, regardless of whether it comes from external content or not.

Common example:

// url?nome=wallace 
isset($_GET['nome']); // true

But if I do this, it will work as well:

// url?nome=wallace
 $_GET['idade'] = 25;
isset($_GET['idade']); // true

See that I declared a value for variable $_GET , which did not exist in the url, but only in the code, and isset detected it there, as expected.

Now see the difference from filter_input

//url?nome=wallace
filter_input(INPUT_GET, 'nome'); // 'wallace';

Already in this case:

$_GET['idade'] = 25;
filter_input(INPUT_GET, 'idade');// bool(false)

Notice that filter_input is not "cheated" by declaring a value within array $_GET .

Thus, filter_input actually checks whether the content exists externally via the GET method. Already isset only checks whether the value exists or not.

The same case applies to the filter_has_var function. So here's a reason to use it instead of isset ;

I thought it was important to point this out here.

    
30.10.2015 / 16:37
2

There is a bug (reported on 3/24/2012) related to the filter_input() function. Some $_SERVER values are not displayed correctly. The code snippet below shows the keys where the problem occurs:

foreach ($_SERVER as $key => $value) {
    if (filter_input(INPUT_SERVER, $key) != $value) {
        echo $key;
    }
}

The keys REQUEST_TIME and REQUEST_TIME_FLOAT will be displayed. For these two cases you should not use filter_input() , using "traditional" access with:

$_SERVER['REQUEST_TIME'];

The filter_has_var() function is also affected by this bug .

    
30.10.2015 / 17:32