Pass a value into filter_input() using variable

3.6k views Asked by At

Can anyone please explain, why do I get very strange warning:

filter_input() expects parameter 1 to be long, string given

when executing the code, that is part of my class and which seems perfectly fine:

public static function Input($type, $data, $filter = 'FILTER_SANITIZE_SPECIAL_CHARS')
  {
    $type = 'INPUT_' . $type;
    return filter_input($type, $data, $filter);
  }

In case I change it to, for example:

return filter_input(INPUT_POST, $data, $filter);

Then the warning goes to:

filter_input() expects parameter 3 to be long.

Everything works just fine if I use:

return filter_input(INPUT_POST, $data, FILTER_SANITIZE_SPECIAL_CHARS);


I realize that on PHP: filter_input - Manual in description it's stated:

Description

mixed filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )

Parameters

type
   One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.


Questions:

  1. Why it's said in manual filter_input ( int $type , - when neither INPUT_GET nor INPUT_POST and etc are INTEGERS.
  2. Is there a way to pass a value into filter_input using variable?
3

There are 3 answers

1
deceze On BEST ANSWER

What you're supposed to use there are constants. These constants have integer values. So the documentation is entirely correct, INPUT_GET is an integer. Try var_dump(INPUT_GET).

If you need to get a constant value from a string, use constant():

echo constant('INPUT_' . $type);
2
Rico Sonntag On

INPUT_POST and INPUT_GET are defined as follows:

/**
 * POST variables.
 * @link http://www.php.net/manual/en/filter.constants.php
 */
define ('INPUT_POST', 0);

/**
 * GET variables.
 * @link http://www.php.net/manual/en/filter.constants.php
 */
define ('INPUT_GET', 1);
3
sergio On

Here the problem. When you concatenate 'INPUT_' with variable it bacame a string, see example:

echo $type = 'INPUT_' . 'POST'; // give you a string INPUT_POST

echo INPUT_POST; //give you 0

That's why :

filter_input() expects parameter 1 to be long, string given