Search code examples
phpwhitelist

Using a whitelist on user input


I have a a simple form to login using a username and password. I want to apply a whitelist to allow only certain characters. I dont know if anybody requires this but here is the code to retrieve the username and password:

$stmt = $conn2->prepare("SELECT username FROM users WHERE username = ? AND password = ?");

$stmt->bind_param("ss", $username, $password);      
$stmt->execute();
$stmt->store_result();

Do I incorporate something like this:

preg_replace( "/[^a-zA-Z0-9_]/", "", $stringToFilter );

If so, where do I include it within my code? And what happens if a user tries to input something other than what is in the whitelist?

ADDED: Ok well what about if it is during registration and it is using INSERT to store username and password?

//insert data
$stmt = $conn2->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");

//bind the parameters
$stmt->bind_param('sss', $username, $email, $password);

Solution

  • Add the filtering code before your INSERT during registration. Check that the string is not empty after filtering, so that a username of "!!*&%$#()*&#$" does not get inserted as a blank string.

    $username_clean = preg_replace( "/[^a-zA-Z0-9_]/", "", $_POST['username'] );
    
    if (!strlen($username_clean)){
    
        die("username is blank!");
    }
    
    $stmt = $conn2->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param('sss', $username_clean, $email_clean, $password_clean);