【问题标题】:Why can I not use filter_input to get information from a form where $_get works just fine为什么我不能使用 filter_input 从 $_get 工作正常的表单中获取信息
【发布时间】:2019-09-13 10:18:47
【问题描述】:

我正在使用带有表单的 get 方法,以便将复选框状态信息存储到数组中

我尝试使用 filter_input 行顺序从每个复选框中获取信息并将其存储到一个数组中,当替换为 $_get 时一切正常,但我被告知不要使用 $_get安全。

<form action="" method="get">
<input type="checkbox" name="1">Show Name<br>
<input type="checkbox" name="2">Show Category<br>
<input type="checkbox" name="3">Show Type<br>
<input type="submit" value="Submit">
</form>

<?php
$formArray = array();
$x = 1;
while ($x < 4) {
    if (isset($_GET[$x]))  {    
        $formArray[$x] = filter_input(INPUT_GET, "$x", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH)  
    }
    else {
        $formArray[$x] = "off";
    }
    $x = $x + 1;
}
?>

然后数组应该存储“on”或“off”的值,但它只是留空,正如我在替换为“$formArray[$x] = $_GET["$x"];”时提到的那样,程序运行 100% 正确

【问题讨论】:

  • isset() 的参数必须是一个变量。只需使用if(filter_input(...))
  • 感谢您创建MCVE

标签: php html arrays filter get


【解决方案1】:

您误用了 filter_input,

filter_input的核心实现如下,

$b = isset($_GET['b']) && is_string($_GET['b']) ? $_GET['b'] : '';

您的元素名称是一个整数。因此,如果 name 不是字符串,filter_input 将返回 false,如果 name 未设置,则返回 null。

我已经修改了你的 sn-p 以使其工作,

<form action="" method="get">
<input type="checkbox" name="t1">Show Name<br>
<input type="checkbox" name="t2">Show Category<br>
<input type="checkbox" name="t3">Show Type<br>
<input type="submit" value="Submit">
</form>
<?php
    if (isset($_GET)) {
        $formArray = [];
        $x         = 1;
        while ($x < 4) {
            if (isset($_GET['t' . $x])) {
                $formArray[$x] = filter_input(INPUT_GET, 't' . $x, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
            } else {
                $formArray[$x] = "off";
            }
            $x = $x + 1;
        }
        echo "<pre>";
        print_r($formArray);
        die;
}
?>

如果选中 2,
输出:-

Array
(
    [1] => off
    [2] => on
    [3] => off
)

您使用的过滤器标志是用于携带的数据元素。

doc.

【讨论】:

  • 这在我看来就像filter_input 中的一个错误,如果变量名是数字,为什么它返回 NULL ???
  • 拉斯穆斯可能会回答这个问题:D。
  • 拉斯穆斯是谁?
猜你喜欢
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多