php POST 变量数组和 filter_input

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19637210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:48:37  来源:igfitidea点击:

POST Variable Array and filter_input

phparraysvariablespostinput

提问by jterry

While using filter_input, I'm not able to pull in a POSTarray variable. The POSTinput:

使用时filter_input,我无法引入POST数组变量。该POST输入:

type              => 'container',
action            => 'edit',
data[display]     => 1,
data[query_limit] => 100

I can access the datavariable from the $_POSTsuperglobal correctly as an array, but the filter_inputfunction returns nothing:

我可以作为数组正确地data$_POST超全局访问变量,但该filter_input函数不返回任何内容:

$data   = $_POST['data']; // Working, woot
$data   = filter_input(INPUT_POST, 'data'); // returns null, should return array
$action = filter_input(INPUT_POST, 'action'); // returns "edit" (correctly)

Is it not possible to use filter_inputfor a POSTarray variable?

不能filter_input用于POST数组变量吗?

回答by reformed

FILTER_REQUIRE_ARRAYwill return false if the POSTvariable contains a scalar value. If you're unsure or just intend on the POSTvariable accepting both scalar and array values, use FILTER_FORCE_ARRAYinstead, which will treat any input as an array, essentially casting scalar values accordingly.

FILTER_REQUIRE_ARRAY如果POST变量包含标量值,则返回 false 。如果您不确定或只是打算POST接受标量和数组值的变量,请FILTER_FORCE_ARRAY改用,它将任何输入视为数组,基本上相应地转换标量值。

$data = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_FORCE_ARRAY);

回答by J?rgen Rudolph L?ker

I have used FormData in javascript and post the fields with jquery ajax. The way I receive all these field is:

我在 javascript 中使用了 FormData 并使用 jquery ajax 发布了字段。我收到所有这些字段的方式是:

$arrFields = array('field1','field2','field2','field3', 'field4','field5');
foreach($arrFields as $field){
   $params[$field] = filter_input(INPUT_POST, $field, FILTER_DEFAULT);
}
var_dump($params);

Then I will get all the data into an array which I can pass on...

然后我会将所有数据放入一个我可以传递的数组中......

回答by Goddard

Alternatively you can do your filtering in one shot...for example

或者,您可以一次性完成过滤……例如

$MY_INPUT = filter_input_array(INPUT_POST, [
    "item_id" => FILTER_SANITIZE_NUMBER_INT,
    "item_string_code" => FILTER_SANITIZE_STRING,
    "method" => FILTER_SANITIZE_STRING,
    "item_id_array" => array(
        'filter' => FILTER_SANITIZE_NUMBER_INT,
        'flags' => FILTER_REQUIRE_ARRAY
    )
]);

The result is almost the same as the post data in terms of what you get back except instead of the global $_POST being your variable it will be $MY_INPUT in this case.

结果与您返回的内容几乎相同,除了全局 $_POST 作为您的变量之外,在这种情况下它将是 $MY_INPUT。