PHP - 清理数组的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4861053/
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 16:07:58  来源:igfitidea点击:

PHP -Sanitize values of a array

phparraysmultidimensional-arraysanitization

提问by Alex

I have a array, which comes from $_POST[]and can have other arrays in it as values, like:

我有一个数组,它来自$_POST[]并且可以在其中包含其他数组作为值,例如:

array(
 'title' => 'Title',
 'data' => array(
             'hdr' => 'Header'
             'bdy' => 'Body'
           ),
  'foo' => array(1, 23, 65),
  ...
)

How can I sanitize all values of this big array? for eg. apply a strip_tags()to values like Title, Header, Body, 1, 23, 65etc ?

如何清理这个大数组的所有值?例如。将 astrip_tags()应用于TitleHeaderBody12365等值?

采纳答案by kieran

Have a look at array_map

看看array_map

<?php  
$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
);

$b = array_map("strip_tags", $a);
print_r($b);
?>

Update for 2D array:

二维数组的更新:

function array_map_r( $func, $arr )
{
    $newArr = array();

    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }

    return $newArr;
}

Usage:

用法:

$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
); 

$ar =array_map_r('strip_tags', $a);
print_r($ar);

Note I found this just by searching the comments for Dimension

请注意,我只是通过搜索Dimension的评论发现了这一点

回答by Alfred

Just use the filter extension.

只需使用过滤器扩展名

/* prevent XSS. */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

This will sanitize your $_GETand $_POST.

这将消毒您的$_GET$_POST

回答by Kemo

function strip($string, $allowed_tags = NULL)
{
    if (is_array($string))
    {
        foreach ($string as $k => $v)
        {
            $string[$k] = strip($v, $allowed_tags);
        }
        return $string;
    }

    return strip_tags($string, $allowed_tags);
}

Just an example of a recursive function, for stripping tags in this case.

只是一个递归函数的例子,用于在这种情况下剥离标签。

$arr = strip($arr);

回答by Paris Z

This looks ok, but please comment if it can be improved or has any misgivings:

这看起来不错,但如果可以改进或有任何疑虑,请发表评论:

$_GET =filter_var_array($_GET);
$_POST=filter_var_array($_POST);

回答by Marc Tremblay

Let's say we want to sanitize the $_POST array:

假设我们要清理 $_POST 数组:

foreach($_POST as $k=>$v) {$_POST[$k] = htmlspecialchars($v);}

foreach($_POST as $k=>$v) {$_POST[$k] = htmlspecialchars($v);}

This simple. Isn't it?

这个简单。不是吗?