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
POST Variable Array and filter_input
提问by jterry
While using filter_input
, I'm not able to pull in a POST
array variable. The POST
input:
使用时filter_input
,我无法引入POST
数组变量。该POST
输入:
type => 'container',
action => 'edit',
data[display] => 1,
data[query_limit] => 100
I can access the data
variable from the $_POST
superglobal correctly as an array, but the filter_input
function 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_input
for a POST
array variable?
不能filter_input
用于POST
数组变量吗?
回答by jbrtrnd
Try :
尝试 :
$data = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
Links:
链接:
http://php.net/manual/en/function.filter-input.php
http://php.net/manual/en/function.filter-input.php
回答by reformed
FILTER_REQUIRE_ARRAY
will return false if the POST
variable contains a scalar value. If you're unsure or just intend on the POST
variable accepting both scalar and array values, use FILTER_FORCE_ARRAY
instead, 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。