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