Lesson 3 of 9 · 23m
XSS: Escape for the Context You Are Actually In
Cross-site scripting is an output-encoding failure — HTML, attributes, JavaScript, URLs, and rich text each need a different defense.
Cross-site scripting is what happens when a value meant to be displayed becomes instructions. PHP teams often describe this as "forgot to sanitize," but sanitation is the wrong mental picture. You are not washing one string until it is universally clean. You are encoding a value for the precise parser that is about to consume it.
The default case: HTML body text
If you are echoing plain text into HTML, encode it at the output point:
echo '<p>' . htmlspecialchars($comment, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</p>';ENT_QUOTES encodes both quote types. ENT_SUBSTITUTE replaces invalid UTF-8 sequences instead of returning an empty string. Put the encoding at the template boundary, not deep inside business logic. A template should be unable to forget safety casually.
Attributes are a different parser
Even encoded text can become dangerous when placed in unusual attributes. Event handlers such as onclick must never contain untrusted data. URLs need both scheme validation and encoding:
function safe_url(string $url): ?string {
if (parse_url($url, PHP_URL_SCHEME) !== 'https') return null;
return htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}javascript: does not become safe because you encoded the quotes. It is a dangerous scheme before HTML parsing even begins.
JavaScript context: do not string-concatenate programs
The classic factory is const name = '<?php echo $name; ?>'; inside a script block. Even with htmlspecialchars, you are constructing JavaScript syntax with string concatenation. Serialize data instead:
<script>
const name = <?php echo json_encode($name, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
</script>Better still, put data in an encoded HTML attribute or endpoint and let JavaScript read it as data. Do not build source code out of user input.
Rich text requires an actual sanitizer
If users are allowed HTML — comments, signatures, knowledge-base posts — allowlist tags and attributes with a mature library such as HTMLPurifier. Writing a regex to strip <script> is a rite of passage into failure: malformed tags, SVG animation elements, encoded entities, attributes, and browser parser repair all conspire against you.
Content Security Policy is the second wall
CSP will not fix a bad template, but it can make exploitation much harder:
header("Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'");Start with report-only mode on a complex legacy application, collect violations, then enforce. Nonces or hashes can permit intentional inline scripts; avoid broad allowances such as unsafe-inline unless you are consciously accepting most of the risk.
Field notes
- Encode late. If you encode on input, you corrupt data for non-HTML consumers such as email, CSV exports, and PDF generation.
- DOM-based XSS happens after PHP hands safe-looking data to unsafe JavaScript sinks such as
innerHTML; audit frontend code too. - Template engines help only when autoescaping is enabled and developers are not bypassing it with raw-output helpers.
"inside an attribute and</script>inside inline JavaScript break different assumptions; one escaping rule does not cover both.
Was this lesson helpful?