Lesson 7 of 8
Not started
Cross-Site Scripting (XSS) Defense in PHP
Understand stored, reflected, and DOM-based XSS, and how output encoding and CSP stop them.
What XSS is
Cross-Site Scripting (XSS) lets an attacker run JavaScript in your users' browsers by smuggling script into content your page renders. The three classic forms:
- Stored — malicious script is saved (e.g. in a comment) and served to every visitor.
- Reflected — script is bounced off the server from a crafted URL or form.
- DOM-based — client-side JavaScript writes untrusted data into the page.
Output encoding is the core defense
Encode data at the point you output it, for the context it lands in:
// HTML body context
echo htmlspecialchars($comment, ENT_QUOTES | ENT_HTML5, 'UTF-8');
Different contexts (HTML attribute, JavaScript, URL, CSS) need different encoding. Never drop untrusted data straight into a block.
Layered protections
- Content-Security-Policy (CSP) — a response header that restricts where scripts may load from, blocking most injected script even if encoding is missed.
- HttpOnly cookies — stop JavaScript from reading session cookies, limiting the damage of any XSS.
- Input validation — reject obviously malformed input early.
- Templating engines (Twig, Blade) auto-escape by default — prefer them over manual
echo.
What it means for you
XSS turns your own site into a weapon against your users. Treat every piece of user-controlled data as hostile until it is encoded for its exact output context, and add CSP as a safety net.