phpfilter-input

Pass a value into filter_input() using variable


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?

Solution

  • 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);