iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

These examples are paired vulnerable + fixed snippets so you can recognise the bug pattern and the defence at once. The vulnerable variants run in a sandboxed authorised lab only. In production code, ship the fixed variants and treat any innerHTML/echo of untrusted data as a defect to escalate.

Three XSS patterns and their defences

EXAMPLE
<!-- 1. Reflected XSS via PHP echo -->
<!-- VULNERABLE -->
<?php /* echo $_GET['q']; -- never do this */ ?>

<!-- FIXED: htmlspecialchars with ENT_QUOTES + UTF-8 -->
<?php
$q = isset($_GET['q']) ? $_GET['q'] : '';
echo htmlspecialchars($q, ENT_QUOTES | ENT_HTML5, 'UTF-8');
?>

<!-- 2. DOM-based XSS via innerHTML -->
<script>
// VULNERABLE: hash fragment goes straight into the DOM
// document.getElementById('out').innerHTML = location.hash.slice(1);

// FIXED: textContent never parses HTML
document.getElementById('out').textContent = location.hash.slice(1);
</script>

<!-- 3. Stored XSS in a Blade comment field -->
{{-- VULNERABLE: {!! $comment->body !!} bypasses escaping --}}
{{-- FIXED: default {{ }} escapes HTML --}}
<div class='comment'>{{ $comment->body }}</div>

<!-- 4. Defence in depth: Content-Security-Policy -->
<!-- Set on the response, blocks inline script even if an injection slips through -->
<!-- Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none' -->

Why it matters

CSP is not a substitute for escaping — it is a second wall behind the first. Strict CSP with per-request nonces neutralises most reflected and stored XSS even when an output-encoding bug slips through code review.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// 1) Replace innerHTML with textContent. 2) Switch to a templating framework.
// 3) Add CSP + Trusted Types. 4) Add DOMPurify for rich text.
// 5) Make HttpOnly + SameSite the default for session cookies.
Try it Yourself »

Discussion

Loading…