If I'm going to store in my database a user-entered string that will eventually make it into a webpage, should I html-escape it first?

I think the answer is no. Databases have no trouble storing arbitrary strings of data. Security problems occur only when we try to put that arbitrary string into an HTML page, so that is where the risk should be mitigated.

However, for some reason, I feel like that "best practice" is to escape everything *before* putting it into a database.

@philipwhite I guess that's because you're trying "sanitise user input" and doing that at user input time gives good locality.

Follow

@sjb
Yes. On input time, sanitize (if the field is supposed to be only alphanumeric, make it alphanumeric). On output time, escape.
If the users want to enter raw html into the field, they should just know that it's going to get escaped.
Escaping before putting into the database is just going to end you up with a bunch of double escaping problems. (Double escaping is not best practice).
@philipwhite

Sign in to participate in the conversation
Librem Social

Librem Social is an opt-in public network. Messages are shared under Creative Commons BY-SA 4.0 license terms. Policy.

Stay safe. Please abide by our code of conduct.

(Source code)

image/svg+xml Librem Chat image/svg+xml