编程语言
首页 > 编程语言> > php-使用白名单对用户输入进行消毒

php-使用白名单对用户输入进行消毒

作者:互联网

我有这段代码可以过滤用户输入的名为“ username”的变量:

$username_clean = preg_replace( "/[^a-zA-Z0-9_]/", "", $_POST['username'] );

if (!strlen($username_clean)){

die("username is blank!");

我想在此页面上的每个输入上执行相同的过程,但是我有大约12种不同的输入,因为它是一种注册表格.有没有更简单的方法来对每个输入进行清理和检查,而不是对每个输入应用preg_replace()和if语句?

解决方法:

如果要清理$_POST中的所有元素,则可以只创建一个清理函数并将其应用于具有array_map的所有元素:

$post_clean = array_map("sanitization_function", $_POST);

然后,您将通过$post_clean而不是$_POST访问变量.

它看起来像:

function sanitize($dirty){ 
    return preg_replace( "/[^a-zA-Z0-9_]/", "", $dirty ); 
}

$cPOST = array_map("sanitize", $_POST);

if (!strlen($cPOST['username'])){ 
    die("username is blank!"); 
}

如果只想清理$_POST元素的子集,则可以执行以下操作:

$cPOST = array();
$sanitize_keys = array('username','someotherkeytosanitize');
foreach($_POST as $k=>$v)
{
    if(in_array($k, $sanitize_keys))
    {
        $cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
    }
    else
    {
        $cPOST[$k] = $v;
    }
}

尝试这个:

$cPOST = array();
$sanitize_keys = array('username','someotherkeytosanitize');
for($_POST as $k=>$v)
{
    if(in_array($k, $sanitize_keys))
    {
        $cPOST[$k] = preg_replace( "/[^a-zA-Z0-9_]/", "", $v);
        if(strlen($cPOST[$k]) == 0){ 
            die("%s is blank", $k);
        }
    }
    else
    {
        $cPOST[$k] = $v;
    }
}
# At this point, the variables in $cPOST are the same as $_POST, unless you 
# specified they be sanitized (by including them in the $sanitize_keys array.
# Also, if you get here, you know that the entries $cPOST that correspond
# to the keys in $sanitize_keys were not blank after sanitization.

只要确保将$sanitize_keys更改为要清除的任何变量(或$_POST键)数组即可.

标签:php,sanitization,whitelist
来源: https://codeday.me/bug/20191012/1899647.html