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

use*_*496 2 php sanitization whitelist

我有这个代码清理用户输入名为'username'的变量:

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

if (!strlen($username_clean)){

die("username is blank!");
Run Code Online (Sandbox Code Playgroud)

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

jed*_*rds 5

如果要清理所有元素$_POST,那么您可以创建一个清理函数并将其应用于所有元素array_map:

$post_clean = array_map("sanitization_function", $_POST);
Run Code Online (Sandbox Code Playgroud)

然后,您将通过$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!"); 
}
Run Code Online (Sandbox Code Playgroud)

如果您只想清理$_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;
    }
}
Run Code Online (Sandbox Code Playgroud)

试试这个:

$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.
Run Code Online (Sandbox Code Playgroud)

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