Is it good to use htmlspecialchars() before Inserting into MySQL?

好久不见. 提交于 2019-12-04 02:29:34

As others have pointed out, #2 is the correct answer. Leave it "raw" until you need it, then escape appropriately.

To elaborate on why (and I will repeat/summarise the other posts), let's take scenario 1 to its logical extreme.

What happens when someone enters " ' OR 1=1 <other SQL injection> -- ". Now maybe you decide that because you use SQL you should encode for SQL (maybe because you didn't use parameterised statements). So now you have to mix (or decide on) SQL & HTML encoding.

Suddenly your boss decides he wants an XML output too. Now to keep your pattern consistent you need to encode for that as well.

Next CSV - oh no! What if there are quotes and commas in the text? More escaping!

Hey - how about a nice interactive, AJAX interface? Now you probably want to start sending JSON back to the browser so now {, [ etc. all need to be taken into consideration. HELP!!

So clearly, store the data as given (subject to domain constraints of course) and encode appropriate to your output at the time you need it. Your output is not the same as your data.

I hope this answer is not too patronising. Credit to the other respondents.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!