EthicsComputerCourses
Join training +91 90532 10052

Cross-Site Scripting (XSS) Prevention

HTML · Lesson 106 of 234 Advanced 12 min read Updated

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

KindWhere the input comes fromWhere it becomes codeMain fix
StoredSaved data: a comment, profile name, product reviewEvery page that shows it, for every visitorEncode on output (server)
ReflectedThe current request: ?q= in a search URL, a form fieldThe response to that one requestEncode on output (server)
DOM-basedBrowser-side sources: location, location.hash, postMessage, storageUnsafe JavaScript sinks such as innerHTMLSafe 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.

HTMLOpen in editor
<!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:

  1. textContent shows the whole comment as plain text, tags and all. Nothing runs.
  2. setHTML (in browsers that support it) shows "Great biryani!" in bold. The image with its onerror handler is removed, so the banner stays the same.
  3. 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.

ContextExampleWhat 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 dataA value your script needsNever write it inside <script> code; use a data- attribute or a JSON block
Never safeonclick="...", <script>...</script>, style="...", unquoted attributesDo 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 &#039; 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.

HTMLOpen in editor
<!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 &quot;Chai &amp; Snacks&quot; <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 = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
      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>
Output
HTML text:     Meera&#39;s &quot;Chai &amp; Snacks&quot; &lt;Pune&gt;
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
<?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'));
Output
Kabir&#039;s &lt;b&gt;&quot;Dhaba&quot;&lt;/b&gt; &amp; Co
Pune �( Cafe
string(0) ""
  • ENT_QUOTES encodes both " and ', so the value is safe in single- or double-quoted attributes.
  • ENT_SUBSTITUTE replaces 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:

PHP
<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:

JSON
{"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(), and setTimeout() or setInterval() with a string
  • href, src or action set from user input, which may be a javascript: URL
  • jQuery's .html() and framework escape hatches such as React's dangerouslySetInnerHTML and Vue's v-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):

JavaScript
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).
  • HttpOnly cookies 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 an onclick attribute or a <script> block.
  • Unquoted attributes: value=<?= e($x) ?> can be broken by a space.
  • Building HTML strings with template literals and innerHTML from 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 textContent and createElement(); 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.

PHP
<h1>Results for <?= $_GET['q'] ?></h1>
<input name="q" value=<?= htmlspecialchars($_GET['q']) ?>>
<button onclick="track('<?= htmlspecialchars($_GET['q']) ?>')">Track search</button>
JavaScript
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
PHP
<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>
JavaScript
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?

2. Why is htmlspecialchars() not enough inside onclick="..."?

3. What does htmlspecialchars() return for invalid UTF-8 without ENT_SUBSTITUTE?

4. Users must be able to post bold text and links. What is the safe approach?

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