Why This Happens
XSS occurs when user-supplied data is included in HTML output without proper escaping. Attackers can inject JavaScript that steals cookies, redirects users, or modifies page content. This is one of the most common web vulnerabilities and is entirely preventable with proper output escaping.
The Problem
// VULNERABLE: User input directly in HTML
$name = $_GET['name'];
echo "<h1>Welcome, $name</h1>"; // Attacker: ?name=<script>alert('xss')</script>The Fix
$name = $_GET['name'] ?? 'Guest';
echo '<h1>Welcome, ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</h1>';
// Or create a helper:
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
echo '<h1>Welcome, ' . e($name) . '</h1>';Step-by-Step Fix
- 1
Find unescaped output
Search for echo and print statements that include user input ($_GET, $_POST, database values) without htmlspecialchars().
- 2
Apply htmlspecialchars
Wrap all user-supplied values with htmlspecialchars($value, ENT_QUOTES, 'UTF-8') before outputting them in HTML context.
- 3
Use a template engine
Use a template engine like Twig or Blade that auto-escapes output by default, reducing the chance of missing an escape.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free