2

我有这段代码可以清理名为“用户名”的变量上的用户输入:

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

if (!strlen($username_clean)){

die("username is blank!");

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

4

2 回答 2

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

于 2012-04-10T18:24:54.657 回答
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");
于 2012-04-10T18:24:26.390 回答