Description
Rendering values from a database or other persistent storage as HTML without output encoding can cause stored XSS.
Potential impact
Malicious scripts may run for every user who views the affected page.
Remediation
Encode data at output time, even if it was validated before storage. Use htmlspecialchars for HTML text and quoted ordinary attributes; JavaScript, CSS, and URL values need context-specific protection.
Examples
Before
php
<?php
$row = mysqli_fetch_row($result);
$guestbook .= "<div>Name: {$row[0]}</div>";
After
php
<?php
$row = mysqli_fetch_row($result);
$name = htmlspecialchars($row[0], ENT_QUOTES, 'UTF-8');
$guestbook .= "<div>Name: {$name}</div>";
Explanation:
- Before: Stored data is written into the HTML response without output encoding.
- After: The stored value is HTML-encoded before insertion into the text content of the
divelement.