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

escaping, forms, html

Solution

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.

Problem

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.

Original source