Is there an advantage to using filter_input instead of isset?

Asked

Viewed 11,785 times

27

I’ve always been used to using the isset to check if an external variable is filled and if you are using it.

Example:

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

Now I installed the Netbeans and give me a Warning telling to use the function filter_input.

Example:

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

Is there any advantage in using the function filter_input?

  • 3

    Obs: isset($_GET["pag"]) can cause a warning in php, you are trying to access an index that may not exist (let error_reporting(E_ALL) to see this warning that is usually omitted). it is more correct to use if(array_key_exists("pag", $_GET)) and this function should debate with filter_input

  • 3

    @Leonardobosquett, can say in what situation a warning was fired using isset?

  • 4

    @Leonardobosquett That’s not right, the function isset exists precisely to check if there is an index pag in the matrix $_GET. Note the example of the documentation in: http://php.net/manual/en/function.isset.php

  • @Correct Zuul, it is up to an example in the PHP manual, there are scenarios (also depends on the configuration of PHP) in which these warnings are shown. Here is a case: http://stackoverflow.com/questions/6027455/help-with-undefined-index-and-undefined-variable

  • 5

    @Leonardobosquett The mistakes Undefined index and Undefined variable are shown when we are trying to use a matrix input or a variable that does not exist. With the isset function, this does not happen. The function simply checks if it exists, and only if it exists will check whether the value is null. You can go deeper into this in this answer of SOEN. In short, the function isset serves precisely to avoid mistakes: Undefined index and Undefined variable.

  • 1

    ntebeans triggers Warning due to netbeans platform usage policies. It doesn’t mean that in PHP that’s true either.. is merely due to the framework rules. Another example, Prestashop triggers Warning when trying to use mb_strlen or strlen or other string functions directly in the code. They ask to use the internal Libraries as a way to standardize codes within the framework rules.

Show 1 more comment

6 answers

17


How it can be read in the function documentation filter_input (English):

filter_input - Gets a specific External variable by name and Optionally Filters it

That translated:

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

The advantage in using the function filter_input is the fact that we will not only collect the value we can also in the course of this collection filter the same:

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

Useful for protecting, cleaning or validating user data without using multiple functions and multiple lines of code.

The filter list can be found here:

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

  • Then I can validate the data from a form using only filter_input?

  • 1

    @Jorgeb. we also have the filter_input_array. Take a look at the answer I posted.

  • 2

    @Jorgeb. Validation is a delicate and complex process, PHP filters aim to simplify the whole process but are not 100% effective and may neglect some details. For example, the filter FILTER_VALIDATE_EMAIL does not correctly assume all existing email composing schemes today. And even when updated, this function is outdated because every day there are new schemes to be applied. We can assume that part of the validation work can be performed with the function filter_input, but it is rarely possible to validate everything using the same.

  • 1

    @Zuul for these exceptions that standard filters are not enough we have the FILTER_CALLBACK.

  • @gmsantos Correto, a callback has been implemented to extend the basic functionality provided by the filter in use.

  • @Zuul what happens when the variable "chavePesquisa" is not filled in? Shouldn’t have an if to know if the $search_html was filled? Like this: $locale = ($filter = filter_input(INPUT_GET, "locale")) ? $filter : $_SESSION['idioma'];

  • 1

    @Jorgeb. Whether or not the variable is filled is a separate matter. You should do this check if you are in need and/or subject to it. As a rule, if it comes from a user, never trust, always check! :)

Show 2 more comments

12

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 on the inputs.

the list of validations and cleanups

The use of filter_input() can sometimes simplify validations, for example an age interval, where a child would not pay a bus ticket, or would have a differentiated value in the charge of a meal in 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;
}

9

One thing I don’t think anyone has commented on, but I think it’s important to point out is that filter_input has a big difference from the isset.

The isset will check whether a particular one is existing, 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 too:

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

Note that I declared a value for variable $_GET, which did not exist in the url, but only in the code, and isset detected him there, as was to be expected.

Now look at the difference between filter_input

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

In that case:

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

Realize that filter_input is not "misled" by the declaration of a value within the array $_GET.

So, filter_input really checks if the content exists externally, via GET method. Now isset only checks whether the value exists or not.

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

I thought it important to emphasize this here.

  • Laravel uses filter_has_var?

  • @rray, the Laravel does not use any of these PHP global variables. In fact, it uses HttpFoundation\Request of Symfony. There, the Symfony, in turn, there is such a Request::createFromGlobals, that uses these variables. In my opinion with all this, they do not use. But I think we should all, since it is a new feature

  • 1

    I remember the Laravel has a few methods, has_var or except to filter the inputs, it’s cool.

  • 1

    Ah, yes. It’s worth asking a question about that, huh. Input::only('nome', 'idade', 'cidade'). Just take these three inputs :)

  • Exactly, to prevent malicious arguments in the :D url. I have studied a bit.

9

The advantage in using the filter_input is in the facility to apply filters to your string.

The same result can be obtained with the function filter_var, implementing 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 functions filter_* are few used by beginners, but they are quite useful. In the example above for example, php already validates if the input is an email, without having to resort to Monstrous Regular Expressions.

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


Adapted example of the 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);

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)
  }
}
  • 4

    "are few used by beginners". I wouldn’t say that and I say for myself, I don’t use it because validation is very delicate and PHP has a 'little problem' with some validations - accents that depend on MB functions, numerical validation... That is why I prefer to create my rules. But the explanation is worth +1 :)

  • 1

    @Papacharlie there really are these little problems, but I prefer to treat them as exceptions. But when I run into these little problems we can turn to the good old callback :)

  • 1

    See the flag FILTER_VALIDATE_INT. You get 1e1(10), and he says it’s true because for PHP 1e1 it’s 10, so it’s an INT between 1-10. :)

7

Yes, and a lot of advantage, since with it you "clean" the input data when using the third parameter, which is the filter type. There are several filters that you can replace with manual validations that you used to do, 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
}

Filters, as you can check in the above URL, can be either for validation or to "sanitize" an input.

Remembering that it is available from the version 5.2.0.

4

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

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

Keys will be displayed REQUEST_TIME and REQUEST_TIME_FLOAT. These two cases should not be used filter_input(), using "traditional" access with:

$_SERVER['REQUEST_TIME'];

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.