Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I HTML-escape data and when should I URL-escape data?

When should I HTML-escape data in my code and when should I URL-escape? I am confused about which one when to use...

For example, given a element which asks for an URL:

<input type="text" value="DATA" name="URL">

Should I HTML-Escape DATA here or URL-escape it here?

And what about an element:

<a href="URL" title="URL">NAME</a>

Should URL be URL-escaped or HTML-escaped? What about NAME?

Thanks, Boda Cydo.

like image 433
bodacydo Avatar asked Jan 28 '10 02:01

bodacydo


People also ask

When should you escape data?

Whenever you're outputting data make sure to properly escape it. Escaping is the process of securing output by stripping out unwanted data, like malformed HTML or script tags, preventing this data from being seen as code.

Do I need to escape & in HTML?

Thus, this character will have this specific meaning only. To escape them in pre tag, we need to use &gt; for HTML entity name or > for HTML entity number as a replacement. Ampersand(&): It is reserved for entities such as &nbsp; which is the HTML entity name for non-breaking space.

Why should I escape HTML?

EDIT - The reason for escaping is that special characters like & and < can end up causing the browser to display something other than what you intended. A bare & is technically an error in the html. Most browsers try to deal intelligently with such errors and will display them correctly in most cases.


2 Answers

URL encoding ensures that special characters such as ? and & don't cause the URL to be misinterpreted on the receiving end. In practice, this means you'll need to URL encode any dynamic query string values that have a chance of containing such characters.

HTML encoding ensures that special characters such as > and " don't cause the browser the misinterpret the markup. Therefore you need to HTML encode any values outputted into the markup that might contain such characters.

So in your example:

  • DATA needs to be HTML encoded.
  • Any dynamic segments of URL will need to be URL encoded, then the whole string will need to be HTML encoded.
  • Name needs to be HTML encoded.
like image 115
Nick Higgs Avatar answered Sep 28 '22 23:09

Nick Higgs


HTML Escape when you're writing anything to a HTML document.

URL Escape when you're constructing a URL to call in-code, or for a browser to call (i.e. in the href tag).

In your examples you'll want to 'Attribute' escape the attributes. (I can't remember the exact function name, but it's in HttpUtility).

like image 31
Noon Silk Avatar answered Sep 28 '22 22:09

Noon Silk