I agree that as a general rule this is excellent practice but for something like the user name wouldn't it make for sense to escape it before adding it to the database instead of every time it is displayed? In fact as part of my registration validation I compare the user name with the return from the escape function and if they're not equal I reject the name:
While it would make sense to escape the username before it enters the database, escaping it afterwards helps protect you against XSS attacks that originate *from* your database - for example, if an attacker gained access to your database and hand-entered the data. Rejecting usernames that have special characters in them isn't a bad idea, but it tends to confuse the user - which characters are invalid? Which aren't? It would be more useful if you could tell them which characters were not allowed.
Roy
· 11 months ago
So why not simply do both? Make Account names viable if they are only Numbers and letters( ex A-Z, a-z, 0-9), no other char allowed, as well as escaping the repeating information?
Luke
· 11 months ago
Roy, You could definitely do both - how much you allow or disallow is entirely up to you.
if ($username != htmlspecialchars($username)) {
$err = "name contains invalid characters";
}
database, escaping it afterwards helps protect you against XSS attacks that
originate *from* your database - for example, if an attacker gained access
to your database and hand-entered the data.
Rejecting usernames that have special characters in them isn't a bad idea,
but it tends to confuse the user - which characters are invalid? Which
aren't? It would be more useful if you could tell them which characters were
not allowed.
You could definitely do both - how much you allow or disallow is entirely up
to you.