HTML Encode

Convert characters into HTML entities so they display as text.

If you want a web page to show the text <div> rather than create a div, you have to escape it. HTML encoding converts the characters that mean something structurally into entities that simply display.

The five characters that matter

< and > delimit tags, & begins an entity, and both quote marks delimit attribute values. Encode those five and almost every problem disappears.

The ampersand is the one people forget. It has to be encoded first, because if you encode the angle brackets first you will then encode the ampersands inside the entities you just created, and end up with &amp;lt; displayed on the page. Order matters.

Encoding HTML

  1. Paste the text or markup you want to display literally.
  2. Encode it.
  3. Copy the entity-escaped output.
  4. Paste it into your page, template or CMS field.
  5. View the page to confirm it renders as visible text rather than markup.

The essential entities

CharacterEntityAlso valid
&&amp;&#38;
<&lt;&#60;
>&gt;&#62;
"&quot;&#34;
'&#39;&apos;
non-breaking space&nbsp;&#160;

Encoding is not a security strategy on its own

Escaping output is a genuine and important defence against cross-site scripting, and you should do it. But it has to happen at the right moment — when you render the value into the page — and with the right rules for the context.

Escaping for HTML text is different from escaping for an attribute, which is different again from escaping for JavaScript or a URL. A value that is safe in one context can be dangerous in another. Use your framework’s context-aware escaping rather than encoding everything once on the way into the database.

HTML encoding questions

What is HTML encoding?

Replacing characters that have structural meaning in HTML with entity references, so the browser displays them as text instead of interpreting them as markup.

Which characters must I escape?

At minimum the ampersand, the less-than and greater-than signs, and both quote marks. The ampersand must be escaped first, or you will end up double-encoding the other entities.

Does escaping protect against XSS?

It is an essential part of the defence, but only when applied at output time and with rules appropriate to the context. HTML text, attributes, JavaScript and URLs each need different escaping.

What is the difference between &nbsp; and a normal space?

A non-breaking space prevents a line break at that point and is not collapsed with adjacent spaces. Useful between a number and its unit; overused, it makes text layout unpredictable.

Should I encode before storing or before displaying?

Before displaying. Store the raw value and escape on output, so the same data can be safely rendered into HTML, JSON, a CSV export or an email without being mangled.

Cookie
We care about your data and would love to use cookies to improve your experience.