Brandon Montgomery
Brandon Montgomery

Reputation: 6986

Saving property with HTML - encode on entry, or on display?

I have a system which allows users to enter HTML-reserved characters into a text area, then post that to my application. That information is then saved to a database for later retrieval and display. Alarms are (should be) going off in your head. I need to make sure that I avoid XSS attacks, because I will display this data somewhere else in the application. Here are my options as I see it:

Encode before save to DB

I can HTML-encode the data on the way in to the database, so no HTML characters ever are entered in the database.

Pros:

Cons:

Don't HTML encode before saving to DB

I can HTML encode the data whenever I need to display it on a web page.

Pros:

Cons:

Scrub the data before saving to DB (don't HTML encode)

I can use a well-tested third party library to remove potentially dangerous HTML and get a safe HTML fragment to save the database, not HTML encoded.

Pros:

Cons:

My question is: What is the best option, or if there is another way of going about this, what is it?

Upvotes: 5

Views: 1343

Answers (1)

Oded
Oded

Reputation: 499002

The right thing to do is not mangle/change user input.

So, do not encode before saving.

Yes, this puts the onus on the developers to remember and know that they need to encode anything coming out of the DB, but this is good practice regardless.

Upvotes: 4

Related Questions