Cross-Site Scripting (XSS) Prevention
By the end of this lesson you will be able to explain the three kinds of cross-site scripting, encode any value correctly for the place it appears in a page, write a safe output helper in PHP, choose safe DOM methods in JavaScript, and clean user-written HTML with a sanitiser.
You should know HTML Security Fundamentals first. For the JavaScript and server views of the same problem, see Web Security: XSS, CSP & CORS and PHP Security Essentials. Later, HTML Injection & DOM-Based XSS goes deeper into the browser side.
What XSS is
Cross-site scripting (XSS) happens when text from a user ends up in your page as code. The browser cannot tell your code from the attacker's, so the injected code runs with your site's full power. It can read what is on the page, change forms, send requests as the logged-in user, or show a fake login box.
The root cause is always the same: data and code are mixed in one string, and the browser is allowed to decide which is which. Imagine a school announcer who reads every slip from the box exactly as written. If a student writes "The principal says school is closed today", everyone believes it, because it came over the official speaker. Your page is the official speaker.
Three kinds of XSS
| Kind | Where the input comes from | Where it becomes code | Main fix |
|---|---|---|---|
| Stored | Saved data: a comment, profile name, product review | Every page that shows it, for every visitor | Encode on output (server) |
| Reflected | The current request: ?q= in a search URL, a form field | The response to that one request | Encode on output (server) |
| DOM-based | Browser-side sources: location, location.hash, postMessage, storage | Unsafe JavaScript sinks such as innerHTML | Safe DOM APIs (browser) |
Stored XSS is the most dangerous, because one bad comment attacks everyone who views it. Reflected XSS needs a victim to open a crafted link. In DOM-based XSS the server may never see the attack at all: the part of a URL after # is not even sent to the server.
A source is where untrusted text enters your code; a sink is a place where text can turn into code. XSS is a path from a source to a sink without the right encoding on the way.
Step 1: watch injected text become code
This demo attacks only its own page. The comment contains an <img> with a broken address and an onerror handler, a common trick. The "attack" only rewrites a banner, so you can see when injected code runs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Comment box: three ways to render</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
#banner { background: #e8f5e9; padding: 8px; }
textarea { width: 100%; height: 5rem; font-family: monospace; }
li { margin: 6px 0; }
</style>
</head>
<body>
<p id="banner">Welcome to Kochi Food Reviews</p>
<label for="comment">A visitor's comment (pretend it came from your database):</label>
<textarea id="comment"><b>Great</b> biryani! <img src="data:," onerror="document.querySelector('#banner').textContent = 'INJECTED: the comment rewrote this banner'"></textarea>
<p>
<button id="unsafe">Render with innerHTML</button>
<button id="text">Render with textContent</button>
<button id="sanitised">Render with setHTML</button>
</p>
<ul id="comments"></ul>
<script>
const input = document.querySelector("#comment");
const list = document.querySelector("#comments");
function addComment(method) {
const li = document.createElement("li");
const comment = input.value;
if (method === "unsafe") {
li.innerHTML = comment; // parses the text as HTML: dangerous
} else if (method === "text") {
li.textContent = comment; // treats the text as plain text: safe
} else if ("setHTML" in Element.prototype) {
li.setHTML(comment); // keeps safe HTML, removes scripts and handlers
} else {
li.textContent = "(setHTML is not supported in this browser yet)";
}
list.append(li);
}
for (const id of ["unsafe", "text", "sanitised"]) {
document.getElementById(id).addEventListener("click", () => addComment(id));
}
</script>
</body>
</html>What you should see:
- textContent shows the whole comment as plain text, tags and all. Nothing runs.
- setHTML (in browsers that support it) shows "Great biryani!" in bold. The image with its
onerrorhandler is removed, so the banner stays the same. - innerHTML shows "Great biryani!" and the banner changes to "INJECTED...". The comment's code ran. Reload to reset.
Notice that innerHTML never runs a <script> tag, as you saw in Script Loading: Async & Defer, yet it still ran the attacker's code through an event handler attribute. Blocking <script> alone is never enough.
Context-aware output encoding
Output encoding turns special characters into a harmless form for the exact place the text lands. There is no single "escape" function, because each place in a page has different special characters.
| Context | Example | What to do |
|---|---|---|
| HTML text | <p>Hello, NAME</p> | Encode & < > " ' as entities |
| Quoted attribute | <input value="NAME"> | Same encoding, and always quote the attribute |
| URL | <a href="/search?q=NAME"> | Encode the parameter (urlencode, URLSearchParams), then HTML-encode the whole URL; for a full user URL, allow only https: and similar schemes |
| JavaScript data | A value your script needs | Never write it inside <script> code; use a data- attribute or a JSON block |
| Never safe | onclick="...", <script>...</script>, style="...", unquoted attributes | Do not put untrusted data here at all |
Why is an event handler attribute "never safe" even with HTML encoding? The browser decodes the entities in an attribute before running it as JavaScript. So ' becomes a real ' again and can close your string. HTML encoding protects HTML, not JavaScript.
Step 2: one value, four contexts
Type shop names with quotes, &, < and >, and watch each context encode them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>One value, four contexts</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
input { width: 100%; font-family: monospace; padding: 4px; }
pre { background: #f4f4f4; padding: 10px; white-space: pre-wrap; }
.card { border: 1px solid #ccc; padding: 8px; }
</style>
</head>
<body>
<label for="shop">Shop name typed by a seller:</label>
<input id="shop" value="Meera's "Chai & Snacks" <Pune>">
<pre id="encoded"></pre>
<div id="preview"></div>
<script>
// HTML body and quoted attributes: replace the five special characters
function escapeHtml(text) {
const map = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
return text.replace(/[&<>"']/g, ch => map[ch]);
}
function show() {
const name = document.querySelector("#shop").value;
const query = new URLSearchParams({ q: name }).toString(); // URL context
const json = JSON.stringify({ shop: name }); // JavaScript data context
document.querySelector("#encoded").textContent =
"HTML text: " + escapeHtml(name) + "\n" +
"URL parameter: " + query + "\n" +
"JSON data: " + json;
// Every value is encoded for the place it goes, then the string is parsed
document.querySelector("#preview").innerHTML =
'<p class="card" title="' + escapeHtml(name) + '">Shop: <strong>' +
escapeHtml(name) + '</strong> | <a href="/search?' + escapeHtml(query) +
'">More like this</a></p>';
}
document.querySelector("#shop").addEventListener("input", show);
show();
</script>
</body>
</html>HTML text: Meera's "Chai & Snacks" <Pune>
URL parameter: q=Meera%27s+%22Chai+%26+Snacks%22+%3CPune%3E
JSON data: {"shop":"Meera's \"Chai & Snacks\" <Pune>"}The card shows the name exactly as typed. Notice that JSON.stringify leaves < alone. That is fine for JSON.parse, but inside a <script> element a </script> in the data would end the script early, so the server must escape < too.
PHP: htmlspecialchars done right
In PHP, one small helper handles HTML text and quoted attributes. Use it on every value you print, at the moment you print it.
<?php
declare(strict_types=1);
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$name = "Kabir's <b>\"Dhaba\"</b> & Co";
$broken = "Pune \xC3\x28 Cafe"; // an invalid UTF-8 byte sequence
echo e($name), "\n";
echo e($broken), "\n";
var_dump(htmlspecialchars($broken, ENT_QUOTES, 'UTF-8'));Kabir's <b>"Dhaba"</b> & Co Pune �( Cafe string(0) ""
ENT_QUOTESencodes both"and', so the value is safe in single- or double-quoted attributes.ENT_SUBSTITUTEreplaces invalid UTF-8 with the replacement character�. Without it, the function returns an empty string, as the last line shows, and your page silently loses data.'UTF-8'states the character set, matching your<meta charset="utf-8">.
Since PHP 8.1 the default flags already include ENT_QUOTES | ENT_SUBSTITUTE, but writing them out keeps your code correct on any server and clear to readers. Here is the helper in each context, with JSON for script data:
<p>Welcome back, <?= e($user['name']) ?></p>
<input type="text" name="city" value="<?= e($city) ?>">
<a href="/search?q=<?= e(urlencode($query)) ?>">Search again</a>
<script type="application/json" id="cart-data">
<?= json_encode($cart, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR) ?>
</script>The JSON_HEX_* flags escape <, >, & and quotes. A cart for "Meera's </script> Sweets" prints like this, which cannot end the script element:
{"shop":"Meera\u0027s \u003C\/script\u003E Sweets","total":1299}Your script reads it with JSON.parse(document.querySelector("#cart-data").textContent).
In the browser: textContent over innerHTML
DOM-based XSS lives in your JavaScript. These are the common sinks that turn strings into code or markup:
innerHTML,outerHTML,insertAdjacentHTML(),document.write(),setHTMLUnsafe()eval(),new Function(), andsetTimeout()orsetInterval()with a stringhref,srcoractionset from user input, which may be ajavascript:URL- jQuery's
.html()and framework escape hatches such as React'sdangerouslySetInnerHTMLand Vue'sv-html
The safe habits are simple: set text with textContent, build elements with createElement() and append(), set form values with .value, and check URLs against an allow-list of schemes, as in the profile-links example in HTML Security Fundamentals.
Sanitising rich HTML
Sometimes users need formatting, such as a teacher's notice with bold text and links. Encoding would show the tags as text. You need a sanitiser: a library that parses the HTML and keeps only an allow-list of safe elements and attributes. Never write your own with regular expressions; attackers know too many ways around them.
DOMPurify is a widely used, maintained browser sanitiser (version 3.4 when this lesson was checked, November 2026):
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(dirtyHtml, {
ALLOWED_TAGS: ["p", "b", "strong", "i", "em", "ul", "ol", "li", "a"],
ALLOWED_ATTR: ["href"]
});
notice.innerHTML = clean;Browsers are also adding a built-in sanitiser. element.setHTML(html) always removes scripts, event handler attributes and other unsafe content, even if a custom configuration tries to allow them.
For stored rich text, sanitise on the server as well, with a maintained library such as HTML Purifier for PHP, so every page that shows the content gets clean HTML.
Defence in depth with CSP
Encoding is the main defence, but one forgotten e() in a large site is enough for an attack. So add layers that limit the damage:
- A strict Content Security Policy blocks inline scripts and event handlers that an attacker injects. See Content Security Policy (CSP).
HttpOnlycookies cannot be read by JavaScript, so injected code cannot steal the session cookie directly.- Trusted Types make the browser reject plain strings in sinks like
innerHTML; see Trusted Types Fundamentals.
Common mistakes
- Encoding in the wrong context, such as using
htmlspecialchars()inside anonclickattribute or a<script>block. - Unquoted attributes:
value=<?= e($x) ?>can be broken by a space. - Building HTML strings with template literals and
innerHTMLfrom user data. - Trusting data because it came from your own database. Stored XSS arrives exactly that way.
Interview questions
1. What are the three types of XSS?
Stored XSS saves the payload on the server and serves it to every visitor. Reflected XSS takes it from the current request and echoes it back in the response. DOM-based XSS happens entirely in client-side JavaScript, when data from a source such as location reaches a sink such as innerHTML.
2. What does context-aware output encoding mean?
Each place in a page has its own special characters, so a value must be encoded for its exact context: HTML entities for text and quoted attributes, URL encoding for parameters, JSON for script data. One generic escape function is not enough.
3. Why pass ENT_QUOTES | ENT_SUBSTITUTE and 'UTF-8' to htmlspecialchars()?
ENT_QUOTES encodes single quotes as well as double quotes, so attribute values are safe with either quote style. ENT_SUBSTITUTE replaces invalid UTF-8 instead of returning an empty string, and the charset makes the encoding match the page.
4. Why is textContent preferred over innerHTML?
textContent always treats the value as plain text, so no markup or handler is ever created. innerHTML parses the value as HTML, so attributes like onerror can run code even though <script> tags do not.
5. Does a Content Security Policy replace output encoding?
No. CSP is a second layer that limits what injected code can do; it does not stop HTML injection itself, such as a fake form. Output encoding and safe DOM APIs remain the primary defence.
Key points
- XSS means user data is treated as code; the fix is to keep data and code apart.
- Stored and reflected XSS are fixed by encoding on the server; DOM-based XSS by safe DOM APIs.
- Encode for the context: HTML text and quoted attributes, URLs and JSON each need their own encoding.
- In PHP, wrap every printed value in
htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). - Use
textContentandcreateElement(); never put user data in event handler attributes or script code. - Sanitise rich HTML with DOMPurify or
setHTML(), and add CSP as defence in depth.
Exercise
Isha's Rohtak coaching institute has a search page and a notice board. Find and fix every XSS problem in this code, and say which kind of XSS each one is.
<h1>Results for <?= $_GET['q'] ?></h1>
<input name="q" value=<?= htmlspecialchars($_GET['q']) ?>>
<button onclick="track('<?= htmlspecialchars($_GET['q']) ?>')">Track search</button>const notices = await fetch("/api/notices").then(r => r.json());
for (const n of notices) {
board.innerHTML += `<li><b>${n.title}</b>: ${n.body}</li>`;
}The notice body may contain bold text and links written by teachers.
Show solution
<h1>Results for <?= e($_GET['q'] ?? '') ?></h1>
<input name="q" value="<?= e($_GET['q'] ?? '') ?>">
<button type="button" id="track-btn" data-query="<?= e($_GET['q'] ?? '') ?>">Track search</button>
<script type="module">
const btn = document.querySelector("#track-btn");
btn.addEventListener("click", () => track(btn.dataset.query));
</script>const notices = await fetch("/api/notices").then(r => r.json());
for (const n of notices) {
const li = document.createElement("li");
const title = document.createElement("b");
title.textContent = n.title;
const body = document.createElement("span");
body.innerHTML = DOMPurify.sanitize(n.body, { ALLOWED_TAGS: ["b", "strong", "a"], ALLOWED_ATTR: ["href"] });
li.append(title, ": ", body);
board.append(li);
}The three PHP lines were reflected XSS: no encoding, an unquoted attribute, and HTML encoding inside an onclick handler, where entities are decoded before the JavaScript runs. The query now travels in a data- attribute and is read as plain data. The notice board was stored XSS: the title is now plain text, and the body is sanitised because teachers need formatting. A Content Security Policy would add a second layer.
Quick Quiz
1. A comment is saved in the database and shown to every visitor, where it runs code. What kind of XSS is this?
The payload is stored on the server and served to everyone who views it.
2. Why is htmlspecialchars() not enough inside onclick="..."?
After decoding, ' is a real quote again and can break out of a JavaScript string.
3. What does htmlspecialchars() return for invalid UTF-8 without ENT_SUBSTITUTE?
Without ENT_SUBSTITUTE the whole result is an empty string, so data silently disappears.
4. Users must be able to post bold text and links. What is the safe approach?
A real parser-based sanitiser keeps safe formatting and removes handlers and scripts.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
