使用白名单清理用户输入


Sanitisation on user input using whitelist

我有这段代码,它清理了用户对名为"用户名"的变量的输入:

$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 键)的数组即可。

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

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");