How and when to use Html encode

让人想犯罪 __ 提交于 2019-12-06 07:29:54

问题


I've recently learned that i shouldn't store html encoded data in the database, but i should rather html encode the data that is shown on the screen for the user. No big deal, i have to fix my database records and make some code changes.

But my question is, when should I use html encode and when shouldn't I. For example, within a html table, I'm writing directly from the database to the inner HTML of a column. Without encoding this would be dangerous, I get that.

What about when setting the value of a textbox. It seems to work without having to html encode the value. But I'm not sure why. This is what the textbox look like:

<input type="textbox" value="xxx"/>

But when setting the value to: "/><p style="font-size: 100px;">testing hack</p> The html source will be:

<input type="textbox" value=""/><p style="font-size: 100px;">testing hack</p>

It will look fine though when viewed so the p-tag isn't working as intended by the "hack".

Is anyone getting what I'm trying to aim at :) ? If I do try to html encode something i set to a textbox value, the result will display "&lt" and so on, which is not what I intended.

So in short: Should I only html encode stuff that is set to the innerHtml of html-controls, and not when setting the value of, for example, textboxes?


回答1:


The answer came out of thejh's and my discussion in the comment to the question. I was not sure what to mark as answer so I decided to answer my own question. I hope that's ok.

It seems like when setting a value of an attribute (like the textbox's "value") .NET automatically html encodes the value so there is no need to do this by yourself.

When setting a html controls inner HTML though, it's important that you do html encode the value.

Thanks Thejh, sorry I couldn't up vote anything u wrote.

edit: I can't mark this as the answer for another 2 days.




回答2:


in the case of

<input type="textbox" value="xxx"/>

'xxx' is an attribute, and you should use a different encoding. In ASP.NET it's HtmlAttributeEncode for example.




回答3:


For HTML attributes, encode backslashes and double quotes.

  1. Replace every \ by \\
  2. Replace every " by \"

Oh, by the way: Sometimes PHP does this for you, see here.

This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.



来源:https://stackoverflow.com/questions/4388510/how-and-when-to-use-html-encode

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