Utility Coder
← Back to Blog
Security9 min read

HTML Encoding and Decoding: Essential Web Security Guide

Learn HTML entity encoding to prevent XSS attacks. Understand HTML entities, character references, and proper encoding practices.

By Andy Pham

HTML Encoding and Decoding: Essential Web Security Guide

HTML encoding is critical for web security, preventing XSS attacks by converting special characters into HTML entity equivalents.

What is HTML Encoding?

HTML encoding converts characters that have special meaning in HTML into entity references that display as literal characters.

Why HTML Encoding is Critical

<!-- User enters: <script>alert('XSS')</script> -->

<!-- Without encoding (DANGEROUS!) -->
<div>Hello, <script>alert('XSS')</script></div>

<!-- With encoding (SAFE) -->
<div>Hello, &lt;script&gt;alert('XSS')&lt;/script&gt;</div>

Essential HTML Entities

Character Entity Description
< &lt; Less than
> &gt; Greater than
& &amp; Ampersand
" &quot; Double quote
' &apos; Single quote

HTML Encoding in Different Languages

JavaScript

function htmlEncode(str) {
  const entities = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };
  return str.replace(/[&<>"']/g, char => entities[char]);
}

const userInput = '<script>alert("XSS")</script>';
const safe = htmlEncode(userInput);
// &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

Python

import html

text = '<script>alert("XSS")</script>'
encoded = html.escape(text)
# &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;

decoded = html.unescape(encoded)

PHP

<?php
$text = '<script>alert("XSS")</script>';
$encoded = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
$decoded = htmlspecialchars_decode($encoded, ENT_QUOTES);
?>

XSS Prevention Best Practices

Framework Protection

Most modern frameworks encode by default:

// React (safe by default)
const element = <div>{userInput}</div>;

// Danger: dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: userHtml }} /> // DANGER!

Common Mistakes

Double Encoding

// Wrong
htmlEncode(htmlEncode('Tom & Jerry'));
// Tom &amp;amp; Jerry (wrong!)

// Right
htmlEncode('Tom & Jerry');
// Tom &amp; Jerry

Try Our HTML Tools

Conclusion

HTML encoding is essential for web security. Always encode user input before displaying it.

Share this article