开发者

How and when to use Html encode

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 e开发者_StackOverflow社区xample, 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜