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
htmlspecialcharswithoutENT_QUOTESor a mismatched charset flag reopens doors — always all four arguments.json_encodefailures returnfalse;JSON_THROW_ON_ERRORturns 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: nosniffkeeps the browser from re-classifying yourtext/plainas executable content. One header, no cost.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Money Is Not a Float: Decimals, Rounding and Cents in PHP, Python and JavaScript
I ran the same money math through PHP 8.6, Python 3.15 and Node 26. They round 2.675 differently, bcadd('0.1', '0.2') returns 0, PHP's BcMath\Number turns a float 0.1 into 0 with only a deprecation notice, and JSON.parse quietly changes 9007199254740993 to ...992.
PHP OPcache, Preloading and the JIT, Measured on Laravel: One Setting Is 18x, One Costs You 19%, and the JIT Does Nothing
I ran Laravel 13 on PHP 8.6 FPM under six OPcache configurations and timed every one. OPcache itself was worth 18x, revalidate_freq=0 quietly cost 19%, preloading added 9%, and the JIT that doubles Zend's CPU benchmark moved a real page by 1%.
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...