Sanitisation on user input using whitelist

前端 未结 2 550
星月不相逢
星月不相逢 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: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");
    

提交回复
热议问题