Security•9 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, <script>alert('XSS')</script></div>
Essential HTML Entities
| Character | Entity | Description |
|---|---|---|
| < | < | Less than |
| > | > | Greater than |
| & | & | Ampersand |
| " | " | Double quote |
| ' | ' | Single quote |
HTML Encoding in Different Languages
JavaScript
function htmlEncode(str) {
const entities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, char => entities[char]);
}
const userInput = '<script>alert("XSS")</script>';
const safe = htmlEncode(userInput);
// <script>alert("XSS")</script>
Python
import html
text = '<script>alert("XSS")</script>'
encoded = html.escape(text)
# <script>alert("XSS")</script>
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; Jerry (wrong!)
// Right
htmlEncode('Tom & Jerry');
// Tom & Jerry
Try Our HTML Tools
- HTML Encoder - Encode HTML entities
- HTML Decoder - Decode HTML entities
- HTML Strip Tags - Remove HTML tags
Conclusion
HTML encoding is essential for web security. Always encode user input before displaying it.