0

I am trying to protect my website from xss attacks and I use htmlspecialchars and mysqli_real_escape_string for this.

Now I am trying to let a user login and register, while he can still use signs like < or >.

I am using the following code for the username: By signup:


    $username = mysqli_real_escape_string($mysql,$_POST['username']);
    $username = strtolower($username);
    $username = htmlspecialchars($username);

And for login:


    $username = mysqli_real_escape_string($mysql,$_POST['username']);
    $username = strtolower($username);
    $username = htmlspecialchars(htmlspecialchars($username));
    echo "Username: $username<br>";

When I use a basic alert script at sign up for username, the username gets encrypted by htmlspecialchars and I see this in the database:

&lt;script&gt;alert(\'2\')&lt;/script&gt;

When I try to login it says "Password or Username incorrect!", but the echo at login exactly matches the username in the database.

First I only used one htmlspecialchars at login, but then it would just echo the username and it wouldn't change anything and I couldn't login.

Does anyone know how I can do this?

Max de Boer
  • 262
  • 3
  • 10
  • 2
    You don't need `mysqli_real_escape_string` to avoid xss, this is (a bad way) to prevent SQL injections (prefer using prepared statements) – Cid Feb 01 '20 at 10:05
  • 2
    `htmlspecialchars` is only useful if you plan on displaying the string or outputting it the html. There really isnt a use case for it to be in play to validate a string. – GetSet Feb 01 '20 at 10:50

1 Answers1

1

Do not save the "HTML encoded" username in the database. The username should be as it is be saved in the database since that is the username the user wants to use. You also use this value to compare for the login with a prepared statement like ... WHERE username=?. Having to work with htmlspecialchars and html_decode() for login/registration/lookup/compare purposes all the time will get you a headache.

When you use the username value from the database and want to output it at the medium of your choice you use the escape mechanism of the medium of your choice. As an example, for output the value in HTML you use functions like htmlspecialchars(). This means that when the user registers with a username iluvu<3 you store this value as such in the database (MySQL has not a problem with the < character), but for displaying purposes in HTML you use something like:

echo "Username: ".htmlspecialchars($username)."</br>";
Progman
  • 16,827
  • 6
  • 33
  • 48