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.
0 of 10 checks passed
Your progress is saved on this device.