Sanitisation on user input using whitelist

谁说胖子不能爱 提交于 2019-12-20 03:17:08

问题


I have this code which sanitises user input on a variable called 'username':

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

if (!strlen($username_clean)){

die("username is blank!");

I want to carry out the same process on each input on this page but I have about 12 different inputs since it is a registering form. Is there an easier way to sanitise and check each input instead of applying preg_replace() and the if statement on each one?


回答1:


If you want to sanitize all of the elements in $_POST, then you could just create a sanitization function and apply it to all the elements with array_map:

$post_clean = array_map("sanitization_function", $_POST);

Then you'd access your variables via $post_clean instead of $_POST.

It'd look something like:

function sanitize($dirty){ 
    return preg_replace( "/[^a-zA-Z0-9_]/", "", $dirty ); 
}

$cPOST = array_map("sanitize", $_POST);

if (!strlen($cPOST['username'])){ 
    die("username is blank!"); 
}

If you only wanted to sanitize a subset of the $_POST elements, you could do something like:

$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;
    }
}

Try this:

$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.

Just make sure to change $sanitize_keys to an array of whatever variables (or $_POST keys) you want to sanitize.




回答2:


If the regex and test for failure is the same, you can write a function:

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


来源:https://stackoverflow.com/questions/10094241/sanitisation-on-user-input-using-whitelist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!