Skip to content

Lesson 7 of 14 · 20m

Output Escaping and CSRF: The Two Half-Defenses

Context-aware encoding, javascript: URLs that survive htmlspecialchars, and why SameSite=Lax is a layer, not a wall.

The browser parses your response in a context: HTML text, attribute value, URL, JavaScript string. htmlspecialchars() encodes for exactly one of them — HTML text and quoted attributes. Most XSS ships because somebody encoded for the wrong context, or encoded once and assumed "escaped" is a property of the string rather than a property of where it lands.

Escaping is contextual

echo htmlspecialchars($comment, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');

The flags matter, and the history is embarrassing enough to remember: until PHP 8.1 the default was ENT_COMPAT, which encodes double quotes but leaves apostrophes raw — so htmlspecialchars($x) inserted into a single-quoted attribute stayed XSS-able for decades. PHP 8.1 (November 2021) changed the default to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5. Pass them explicitly anyway; being correct by accident is how bugs get reintroduced on old containers.

Now the part that sinks people: javascript:alert(1) is perfectly encodable text. In an href it executes on click — escaping the string does nothing because the string was never the problem; the URL scheme was.

// htmlspecialchars'd, still XSS:
echo '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">link</a>';

// The fix is a scheme allowlist:
$scheme = parse_url($url, PHP_URL_SCHEME);
if (!in_array($scheme, ['https', 'http', 'mailto'], true)) { $url = '#'; }

strip_tags() is the other half-defense. It removes tags; it doesn't encode anything, and with allowed_tags it keeps the tag and its attributes — <a href="javascript:..."> survives a strip_tags($x, '<a>') intact. strip_tags is for stripping markup out of a comment, not for sanitizing. Encoding and stripping are different operations; the wrong one is worse than none because it looks like a control.

The <script> context is its own world

Embedding JSON in a page — var init = <?= json_encode($data) ?> — fails on </script> inside a string literal, which ends the script element early regardless of JSON validity. json_encode has flags for exactly this:

echo json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);

JSON_HEX_TAG turns < and > into \u003C/\u003E — valid JSON, inert in a script context. And note what doesn't protect you here: htmlspecialchars. Inside <script> the browser isn't parsing HTML entities; it's parsing JavaScript. Wrong context, wrong control.

DOM XSS bypasses all of it — el.innerHTML = userValue is a JS sink that never touches your PHP escaping. If the page has a templating engine, use it: Twig's autoescape is context-aware (html, js, css, url, html_attr strategies) and has been the reference implementation for what "encode by context" actually means. Every manual echo of untrusted data is a decision you made to skip that.

CSRF: the other half of state safety

SameSite=Lax on the session cookie blocks most classic CSRF — the cookie simply doesn't ride cross-site POSTs or subresource requests. What Lax permits is top-level GET navigations. So a GET /admin/delete?id=4 endpoint — which shouldn't exist — remains forgeable by a link. Rule one: state changes never happen on GET. Then the CSRF token: a per-session random value rendered into forms, verified on submit, compared with hash_equals. Check Origin/Sec-Fetch-Site as a second signal. SameSite is a layer; the token is the wall.

Try this

Put ');alert(1);// into a field your app renders inside a single-quoted attribute, and javascript:alert(1) into a URL field. Then fix the flags and add the scheme check. Watching both payloads die is worth more than the section above.

Pitfalls

  • htmlspecialchars without ENT_QUOTES or a mismatched charset flag reopens doors — always all four arguments.
  • json_encode failures return false; JSON_THROW_ON_ERROR turns silent corruption into an exception.
  • CSP (script-src 'self' 'nonce-…') is the second line, not the first — it catches what escaping missed; it doesn't replace escaping.
  • X-Content-Type-Options: nosniff keeps the browser from re-classifying your text/plain as executable content. One header, no cost.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.