问题
I have a website that saves data to a MySQL database
Should I escape the HTML upon inserting it into MySQL or upon displaying it on my website?
Ideally, I'd like to input raw HTML into my database and just sanitize each time I pull from it. Is there any danger in doing it this way?
Example html:<h1>test</h1>
回答1:
typically users won't save HTML, but I don't want them to be restricted. Of course that HTML won't be executed. It will just be displayed
Should I escape the HTML upon inserting it into MySQL or upon displaying it on my website?
Then you don't have HTML to begin with. You have plain text.
Escaping plain text to be injected in HTML is a fast operation and, unless we're talking of 1 GB worth of text in a single row, it doesn't make sense to cache it. If you convert to plain text to HTML before saving it, you no longer have the original text and you're forced to undo the encoding just to not use it in HTML context (e.g., put it in a JavaScript variable or use it as e-mail subject).
来源:https://stackoverflow.com/questions/42141978/mysql-html-sanitization