when to use htmlspecialchars() function?

空扰寡人 提交于 2019-11-26 08:18:49

问题


Hi I was wondering when is the appropriate place to use htmlspecialchars(). Is it before inserting data to database or when retrieving them from the database?


回答1:


You should only call this method when echoing the data into HTML.

Don't store escaped HTML in your database; it will just make queries more annoying.
The database should store your actual data, not its HTML representation.




回答2:


You use htmlspecialchars EVERY time you output content within HTML, so it is interperted as content and not HTML.

If you allow content to be treated as HTML, you have just opened the door to bugs at a minimum, and total XSS hacks at worst.




回答3:


Save the exact thing that the user enters into the database. then when displaying it to public, use htmlspecialchars(), so that it offers some xss protection.




回答4:


Guide - How to use htmlspecialchars() function in PHP

To begin you have to understand 1 simple concept: Render.

What Render is? Render is when the HTML transforms

<b>Hello</b>

to bold like this Hello. That's render.

So...When to use the htmlspecialchars() function?

Wherever you want to render HTML contents. For example, if you are using JQuery and you do this:

$("#YourDiv").html("<b>Hello</b>");

The div contents will be Hello. It rendered the text into HTML.

If you want to display the message in this way (was wrote by user):

<b>Hello</b>

you have to put:

$("#YourDiv").text("<b>Hello</b>");

In that way the Hello will never be rendered.

If you want to load the message (as wrote by user) into a textbox, textarea, etc... You have to put:

<input type="text" class="Texbox1" value="">

<script>
$(".Textbox1").val("<b>Hello</b>");
</script>

That will display

 <b>Hello</b>

Inside the Textbox without problems.

Conclusion:

What ever data the user input into your forms, etc...Save the data as normally. Do not use any function. If user sent 12345 save as it is. Do not filter nothing. You only have to filter when you are going to display the data in the page to the users. YOU, ONLY YOU decide if you want to render or not what the user wrote. *Remember that.

Regards!



来源:https://stackoverflow.com/questions/4882307/when-to-use-htmlspecialchars-function

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