03
Comment History
Comments are persisted in MySQL and rendered below.
No comments have been submitted yet.
What happened?
The application retrieved user-controlled text and inserted
it into the HTML response without output encoding.
A browser interprets the resulting response as HTML.
If the injected value contains executable markup such as a
script element, the browser may interpret and execute it.
With stored XSS, the malicious test value
is saved in the database first and can execute whenever
the affected page displays that stored value.
With reflected XSS, the value comes from
the current request and is reflected directly into the
generated response.
How to fix it
Treat all user-controlled data as untrusted when it crosses
into an HTML context.
htmlspecialchars(
$value,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
Output encoding is context-dependent. This example protects
values being placed into normal HTML text or attribute
contexts. Other contexts, such as JavaScript, CSS, URLs, or
SQL, require their own appropriate handling.
The database layer also uses PDO prepared statements so the
demonstration does not unnecessarily introduce SQL injection.