【问题标题】:Pass a value into filter_input() using variable使用变量将值传递给 filter_input()
【发布时间】:2014-01-08 12:39:51
【问题描述】:

谁能解释一下,为什么我会收到非常奇怪的警告:

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

执行代码时,这是我的课程的一部分,看起来非常好:

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

如果我将其更改为,例如:

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

然后警告转到:

filter_input() expects parameter 3 to be long.

如果我使用,一切正常:

return filter_input(INPUT_POST, $data, FILTER_SANITIZE_SPECIAL_CHARS);


我意识到在PHP: filter_input - Manual 的描述中是这样描述的:

说明

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

参数

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


问题:

  1. 为什么在手册中说 filter_input ( int $type , - INPUT_GETINPUT_POST 等都不是 INTEGERS
  2. 有没有办法使用变量将值传递给filter_input

【问题讨论】:

    标签: php filter-input


    【解决方案1】:

    你应该在那里使用constants。这些常量具有整数值。所以文档是完全正确的,INPUT_GET 是一个整数。试试var_dump(INPUT_GET)

    如果需要从字符串中获取常量值,请使用constant()

    echo constant('INPUT_' . $type);
    

    【讨论】:

    • 是的,如此简单直接!以前从未听说过!它按预期工作!谢谢!
    【解决方案2】:

    这就是问题所在。当您将 'INPUT_' 与变量连接时,它会变成一个字符串,请参见示例:

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

    这就是为什么:

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

    【讨论】:

    • sergio,谢谢,但我不确定你的意思!
    • 当你这样做时: $type = 'INPUT_' 。 $类型;它变成了一个字符串,但不是像 INPUT_POST 这样的常量。
    • 啊,好吧!是的,deceze 已经解释过了! +1 为一个额外的例子!
    【解决方案3】:

    INPUT_POSTINPUT_GET定义如下:

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

    【讨论】:

    • 谢谢你,里科!请您详细说明您的答案!
    • 查看@deceze 答案以获得最终解决方案。我只想指出常量的类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2020-10-30
    • 2013-05-04
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多