Sanitisation on user input using whitelist

前端 未结 2 510
星月不相逢
星月不相逢 2021-01-22 21:31

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

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


        
相关标签:
2条回答
  • 2021-01-22 21:45

    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.

    0 讨论(0)
  • 2021-01-22 21:52

    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");
    
    0 讨论(0)
提交回复
热议问题