Stored XSS

Stored XSS

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>";

htmlspecialchars encodes the name read from the database just before it is inserted as text in the <div>.

References