XSS prevention
Learn to protect against XSS with htmlspecialchars() and output escaping.
What is XSS?
XSS (cross-site scripting) is when an attacker injects HTML or JavaScript into a page. If you echo user input without escaping, a malicious <script> runs and can steal the session.
Defense: escape every output going to the browser with htmlspecialchars(). It turns <, >, quotes and & into HTML entities; the browser shows them as text instead of running them as code.
ENT_QUOTES and ENT_HTML5
By default htmlspecialchars() only escapes double quotes. Single quotes can also be dangerous inside attribute values. With the ENT_QUOTES flag you convert both quote types.
ENT_HTML5 uses HTML5-appropriate entities. Passing "UTF-8" as the third argument makes the encoding explicit. In modern projects always use ENT_QUOTES | ENT_HTML5 for maximum safety.
Exercise Print user input safely
The $userInput holds a malicious script tag. Escape it with htmlspecialchars; use ENT_QUOTES | ENT_HTML5 as the second argument and "UTF-8" as the third. Assign the result to $safe and print it with echo.
Show example solution
Write $safe = htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, "UTF-8");. Then print with echo $safe . "\n";.
Example solution:
<?php
$userInput = '<script>alert("xss")</script>';
$safe = htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, "UTF-8");
echo $safe . "\n";
Test yourself
-
Complete the htmlspecialchars call
$safe = ____($userInput, ENT_QUOTES | ENT_HTML5, "UTF-8");Show answer
$safe = htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, "UTF-8"); -
Match the XSS concepts
- htmlspecialchars
- Escapes special characters
- ENT_QUOTES
- Single and double quotes
- ENT_HTML5
- HTML5 character set
- echo
- Outputs content
-
Which escapes both single and double quotes?
- htmlspecialchars($s)
- htmlspecialchars($s, ENT_COMPAT)
- htmlspecialchars($s, ENT_NOQUOTES)
- htmlspecialchars($s, ENT_QUOTES)
Show answer
htmlspecialchars($s, ENT_QUOTES) — Correct. ENT_QUOTES converts both quote types.