Skip to content

Chapter 29 of 38

XSS Prevention

Encode output by context, sanitize trusted markup, and deploy browser protections.

40 minutes 10 quick checksBy Subha Prasad
Lesson 29 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Cross-site scripting executes attacker-controlled script in another user's browser. The central defense is contextual output encoding at the final rendering point.

Practical example

<?php
function html(string $value): string {
  return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
echo '<p>' . html($comment) . '</p>';

HTML text, attributes, URLs, JavaScript, and CSS require different handling. Avoid placing untrusted data into script contexts. Sanitize only when trusted rich HTML is truly required. CSP, HttpOnly cookies, and framework auto-escaping add defense in depth.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes XSS?
Which PHP term matches this description: Execution of attacker-controlled script in another user's browser.
Which statement best describes output encoding?
Which PHP term matches this description: Escaping data for its exact HTML, attribute, URL, CSS, or JS context.
Which statement best describes htmlspecialchars?
Which PHP term matches this description: HTML text/attribute encoding when configured with appropriate flags and charset.
Which statement best describes CSP?
Which PHP term matches this description: A browser policy restricting permitted script and resource sources.
Which statement best describes trusted HTML?
Which PHP term matches this description: Markup accepted only after robust allowlist sanitization.

0 of 10 checks passed

Your progress is saved on this device.

XSS Prevention | PHP Lesson | Subha Prasad