> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/cross-site-scripting-xss/stored-xss.md).

# Stored XSS

Stored Cross-Site Scripting (Stored XSS), also known as Persistent XSS, occurs when an application stores user-controlled input and later displays it to other users without proper sanitization or output encoding.

Unlike Reflected XSS, where the payload is included in a request and executed immediately, Stored XSS is saved by the application (typically in a database) and automatically executes whenever the affected content is viewed.

***

### Vulnerable PHP Code Example

```php
<?php

$conn = mysqli_connect("localhost", "root", "password", "blog");

$comment = $_POST['comment'];

$query = "INSERT INTO comments(comment) VALUES('$comment')";
mysqli_query($conn, $query);

echo "Comment added successfully";

?>
```

Later, the application displays comments:

```php
<?php

$query = "SELECT comment FROM comments";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['comment'];
}

?>
```

***

### Code Explanation

The application accepts a comment from the user:

```php
$comment = $_POST['comment'];
```

The comment is stored in the database:

```php
$query = "INSERT INTO comments(comment) VALUES('$comment')";
```

Later, when comments are displayed, the application outputs the stored value directly:

```php
echo $row['comment'];
```

Because the output is not encoded or sanitized, any HTML or JavaScript stored in the database will be rendered and executed by the browser.

The vulnerability occurs during the display of the stored content, not during the initial submission.

***

### How to Exploit

1. Identify functionality that accepts and stores user-generated content, such as comments, reviews, profile descriptions, support tickets, or forum posts.
2. Submit content containing HTML or JavaScript.
3. The application stores the supplied content in the database without proper filtering or sanitization.
4. When the stored content is displayed, the application includes it in the page without proper output encoding.
5. The browser interprets the stored content as active code instead of plain text.
6. Every user who views the affected page automatically receives and executes the payload.
7. If an administrator views the affected content, the attack executes with the administrator's session and privileges.
