Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 147 ยท Security

Preventing XSS

Learn how cross-site scripting works and how to stop it in PHP - htmlspecialchars with ENT_QUOTES, escaping for attributes, URLs, JavaScript and CSS, plus CSP.

Cross-site scripting (XSS) happens when an attacker gets their own JavaScript to run on your pages, in your visitors' browsers. To the browser, that script looks like part of your site, so it can do anything your own code can: read the page, submit forms as the user, steal data shown on screen, or replace the login form with a fake one. XSS has been one of the most common web vulnerabilities for over two decades, and PHP's habit of mixing code and HTML makes it easy to create.

The good news: the fix is simple and mechanical. Every time you put a value into HTML, you escape it for the place where it lands. This lesson shows how XSS attacks work, how htmlspecialchars() stops the common case, which places need different escaping (attributes, URLs, JavaScript, CSS), and how a Content-Security-Policy header adds a second line of defense.

It builds on Web Security Basics and the template ideas from PHP and HTML Templates.

How XSS works

A PHP page that echoes user input straight into HTML lets the user write HTML, and HTML can contain scripts. Here's a search page that repeats the search term, with a simulated request. As always in our editor, the output is the HTML source; a browser would render it and run the script.

PHP A reflected XSS hole and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The vulnerable version sends a real <script> element; the browser runs it and sends the victim's cookies to the attacker. The escaped version turns < into &lt; and " into &quot;, so the browser shows the text instead of running it. Escaping doesn't remove anything: the user sees exactly what they typed.

There are three flavors of XSS, and the same escaping prevents the first two:

  • Reflected XSS: the payload is in the request (usually a link the attacker sends to the victim) and the page echoes it back, like the search above.
  • Stored XSS: the payload is saved, in a comment, a profile name or a product review, and served to every visitor who views it. It's more dangerous because victims don't need to click anything unusual.
  • DOM-based XSS: your own JavaScript takes a value (from the URL fragment, for example) and puts it into the page with innerHTML. PHP never sees it; the fix is in the JavaScript (use textContent).

htmlspecialchars, the right way

htmlspecialchars() converts the five characters that are special in HTML into entities:

Character Becomes Why it matters
& &amp; starts an entity
< &lt; starts a tag
> &gt; ends a tag
" &quot; ends a double-quoted attribute
' &#039; ends a single-quoted attribute

Its full signature is htmlspecialchars(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true). The defaults have been good since PHP 8.1, which added ENT_QUOTES (escape both quote types) and ENT_SUBSTITUTE (replace invalid UTF-8 with the replacement character U+FFFD instead of returning an empty string). Before 8.1, single quotes were left alone, which is why older code passes ENT_QUOTES explicitly. Spelling it out is still a good habit, because code gets copied into projects with different settings.

Typing htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') hundreds of times is how escaping gets forgotten, so every PHP project defines a short helper. Most call it e():

PHP An escaping helper and its edge cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows each character converted, the value safely inside a quoted attribute, the double-escaping bug (&amp;lt;b&amp;gt;, which a browser would display as the literal text &lt;b&gt;) and the replacement character for the broken byte. Two rules follow:

  • Escape once, at output. Store the raw text in the database and escape when you print it. If you escape before saving, you'll escape again on output and show &amp; to users, and your data is now HTML-specific when you also need it in JSON, emails or a CSV export.
  • Always quote attributes. htmlspecialchars() protects quoted attributes only. In <input value=<?= e($v) ?>>, a value like x onfocus=alert(1) autofocus needs no quotes or brackets to add new attributes.

strip_tags() is not an XSS defense. It mangles legitimate text (a comment saying "use x<y here" loses part of the text), it doesn't touch quotes, so it does nothing for attributes, and its optional list of allowed tags keeps all their attributes, including onclick. Use htmlspecialchars() for text. For user-written HTML, see the section on rich text below.

Stored XSS in a template

Stored XSS comes from the same mistake, only the data takes a detour through the database. In a template, the short echo tag <?= ?> together with e() keeps escaping readable:

PHP Escaping stored comments in a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both the stored <script> and the attribute-breaking author name come out as harmless text, and Ana's honest < displays correctly. The prepared statement protected the database; escaping protects the page. They're different defenses for different languages, and you need both. Template engines like Twig and Laravel's Blade escape {{ $value }} automatically, which is a big reason to use them in larger projects.

Escape for the context

HTML pages contain several "languages", and each one has its own special characters. htmlspecialchars() is right for text and quoted attributes, but it's not enough in the other contexts:

Where the value goes Example What to do
HTML text <p>VALUE</p> htmlspecialchars()
Quoted attribute <input value="VALUE"> htmlspecialchars(), always with quotes
URL attribute <a href="VALUE"> Validate the scheme (only http/https), then htmlspecialchars()
Part of a URL ?q=VALUE rawurlencode() or http_build_query(), then htmlspecialchars()
JavaScript <script>let x = VALUE;</script> json_encode() with the JSON_HEX_* flags
CSS style="color: VALUE" Allowlist only (for example a regex for hex colors)
Event handler onclick="VALUE" Don't. Use a data- attribute and a separate script

URLs: escaping doesn't stop javascript:

A link to a user's website looks harmless: <a href="<?= e($website) ?>">. But javascript:alert(1) contains no special HTML characters, so escaping leaves it intact, and clicking the link runs the script. The fix is an allowlist of URL schemes:

PHP Safe links and query strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two javascript: variants and the data: URL are rejected, even with odd capitalization and a leading space, because the check parses the scheme rather than searching for a string. In the query string example, http_build_query() encodes the &, spaces and quotes for the URL, and e() then turns the & between parameters into &amp;, which is how it should appear inside an HTML attribute.

JavaScript: use json_encode

Passing PHP data to a script is common: a map's coordinates, a user's settings. Pasting a string between quotes is broken in two ways. A quote ends the JavaScript string early, and the text </script> ends the whole script element, no matter where it appears, because the HTML parser finds it before JavaScript runs. htmlspecialchars() would corrupt the data instead. json_encode() produces a valid JavaScript literal, and the JSON_HEX_* flags turn <, >, &, ' and " into escapes such as \u003C (for <) and \u0027 (for '):

PHP Passing data to JavaScript safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the broken version, the browser's HTML parser ends the script at the first </script> and then runs the attacker's script element. In the safe version, the name contains \u003C\/script\u003E, which JavaScript reads back as the original text but the HTML parser doesn't recognize as a tag. The data-attribute approach is even cleaner, because it keeps all JavaScript in separate files, which also helps with the CSP header below. More about these flags is in the JSON lesson.

CSS: allowlist or nothing

CSS can load URLs and, in old browsers, even run script, and its escaping rules are complex. Don't put free text into style attributes or <style> blocks. If users can choose a color, accept only a strict format, such as preg_match('/^#[0-9a-f]{6}$/i', $color), or let them pick from a fixed list of theme names.

Rich text: when users write HTML

Sometimes users are supposed to format text: a blog editor, a forum with bold and links. Escaping would show their tags as text. Don't try to filter HTML with regular expressions or strip_tags(). Two safe approaches:

  • Use a limited markup language such as Markdown, convert it to HTML with a library configured to escape raw HTML (league/commonmark with 'html_input' => 'escape'), and then sanitize the result.
  • Sanitize with a real HTML sanitizer such as symfony/html-sanitizer or HTML Purifier. They parse the HTML into a tree like a browser does and rebuild it with only an allowlist of tags, attributes and URL schemes.

Both are Composer packages, so they can't run in our editor, but the principle is the one from the previous lesson: allowlist, never blocklist.

Content-Security-Policy: the safety net

Even careful teams miss an escape eventually. A Content-Security-Policy (CSP) response header tells the browser which scripts it may run. A strict policy allows only scripts that carry a random nonce generated for each response, so an injected <script> without the nonce is blocked, and inline event handlers like onerror="..." are blocked too:

PHP A CSP header with a nonce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The nonce changes on every run, just as it must change on every response; a fixed nonce would be useless. 'strict-dynamic' lets your trusted scripts load further scripts, which makes the policy practical with modern bundles. object-src 'none' blocks old plugins, base-uri 'none' stops an injected <base> tag from redirecting your relative script URLs, and frame-ancestors controls who may embed your page in a frame.

A few practical tips:

  • Roll out a new policy with Content-Security-Policy-Report-Only first. Browsers then report violations without blocking anything, so you can fix your own inline scripts before enforcing it.
  • CSP is a second layer. It reduces the damage of a missed escape; it never replaces escaping.
  • Pages that are cached (by a CDN, for example) can't use a per-response nonce. They can allow scripts by hash ('sha256-...') or only from your own domain.
  • Mark session cookies HttpOnly so that even a successful XSS can't read them with document.cookie (see Cookies). The attacker's script can still act as the user while the page is open, so this limits damage but doesn't prevent it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An attacker posts a comment containing a script tag, and every visitor who opens the article runs it. What kind of XSS is this?

    The payload is saved on the server and served to every visitor who views the page, which is stored (persistent) XSS.
  2. 2. What does htmlspecialchars('<a href="x">Tom & Jerry</a>') turn the ampersand into?

    The ampersand becomes the HTML entity &, along with < > and the quotes. %26 is URL encoding and & is JSON/JavaScript escaping.
  3. 3. A profile link is printed as <a href="<?= e($website) ?>"> with a working e() helper. Is it safe?

    Escaping protects the attribute's syntax, not its meaning. Allow only http and https URLs.
  4. 4. Which is the right way to put a PHP string into an inline script?

    json_encode() creates a valid JavaScript literal, and the HEX flags make sure a </script> sequence or a quote can't end the script element or the string.
  5. 5. When should you escape user input for HTML?

    Store raw data and escape at output. Escaping before saving leads to double escaping and data that only works in HTML. CSP is a safety net, not a replacement.

Summary

  • XSS lets an attacker run JavaScript on your pages. Reflected XSS comes from the request, stored XSS from saved data, DOM-based XSS from your own JavaScript.
  • Escape every value at output with htmlspecialchars($v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), usually through a short e() helper. Since PHP 8.1 those flags are the default.
  • Store raw data, escape once at output, and always quote attributes. strip_tags() isn't a defense.
  • Escape for the context: allowlist URL schemes for href/src, encode URL parts with rawurlencode()/http_build_query(), pass data to JavaScript with json_encode() and the JSON_HEX_* flags, and never put free text into CSS or event handlers.
  • For user-written HTML, use Markdown with escaping or a real HTML sanitizer library.
  • A Content-Security-Policy with a per-response nonce blocks injected scripts as a second layer; HttpOnly cookies keep session IDs out of reach of scripts.

Next: Preventing CSRF