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

时间:2012-04-10 18:19:52

标签: php sanitization whitelist

我有这个代码可以清除用户对名为'username'的变量的输入:

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

if (!strlen($username_clean)){

die("username is blank!");

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

2 个答案:

答案 0 :(得分:5)

如果要清理$_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键)的数组。

答案 1 :(得分:1)

如果正则表达式和失败测试相同,则可以编写函数:

function validate($input, $input_name) {
  $clean_input = preg_replace( "/[^a-zA-Z0-9_]/", "", $input );
  if (!strlen($username_clean)){
    die("$input_name is blank!");
  }
  return $clean_input;
}
validate($_POST['username'], "Username");
相关问题