-->

环境卫生上使用白名单的用户输入(Sanitisation on user input using w

2019-06-25 07:56发布

我有这样的代码sanitises上一个名为“用户名”变量用户输入:

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

if (!strlen($username_clean)){

die("username is blank!");

我要执行同样的过程在这个页面上的每个输入,但我有大约12个不同的输入,因为它是一个登记表。 有没有消毒和检查每个输入而不是应用的preg_replace(更简单的方法),并在每一个if语句?

Answer 1:

如果你想清理所有的元素$_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键)要清理的阵列。



Answer 2:

如果正则表达式和测试失败是一样的,你可以写一个函数:

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


文章来源: Sanitisation on user input using whitelist