Back to results for “Validation”
PHP › Security

What is cross site scripting, commonly called XSS, and how does properly escaping output help prevent it?

Beginner

Answer

Cross site scripting occurs when an attacker manages to inject malicious script code into a web page that is then executed in another user's browser, often by submitting that script as input somewhere that later gets displayed back to other visitors without being properly escaped, and escaping output using a function like htmlspecialchars before displaying any user supplied data ensures that special characters are converted into their safe text equivalents, so the browser renders the input as plain text rather than executing it as code.
echo htmlspecialchars($userComment, ENT_QUOTES, 'UTF-8');
Real-world example A comment section on a blog escapes every submitted comment before displaying it, ensuring that if a visitor submits a comment containing script tags, it appears harmlessly as plain text to other readers instead of actually running in their browsers.

Common follow-ups: What is the difference between stored and reflected cross site scripting?;Are there any situations where escaping output is not enough to prevent an attack?