Pass a value into filter_input() using variable

落花浮王杯 提交于 2019-12-02 03:33:16

问题


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?

回答1:


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:


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



回答3:


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


来源:https://stackoverflow.com/questions/20995923/pass-a-value-into-filter-input-using-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!