Escape Output
What is Cross-Site Scripting (XSS)?
Section titled “What is Cross-Site Scripting (XSS)?”XSS is a security vulnerability where attackers inject malicious scripts into web pages. When users visit the page, the script runs in their browser and can steal cookies, session data, or perform actions on their behalf.
What is Output Escaping?
Section titled “What is Output Escaping?”Output escaping converts dangerous characters (like <, >, ", ') into safe HTML entities before displaying them. This prevents injected scripts from executing.
For example:
<script>becomes<script>- The browser displays the text instead of running it as code
How to Escape Output
Section titled “How to Escape Output”Use htmlspecialchars() to escape any dynamic content:
$userInput = "<script>alert('XSS!');</script>";$safe = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');echo $safe;// Displays: <script>alert('XSS!');</script>Always use these parameters:
ENT_QUOTES- Escapes both single and double quotes'UTF-8'- Proper character encoding
The Key Rule
Section titled “The Key Rule”Escape output, not input. Store raw data in the database, escape when displaying.
// Store raw data$comment = $_POST['comment'];$stmt->execute(['comment' => $comment]);
// Escape when displayingecho htmlspecialchars($row['comment'], ENT_QUOTES, 'UTF-8');Example
Section titled “Example”// Helper function for escapingfunction e($string) { return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');}
// Display user data safelyecho "<p>Welcome, " . e($username) . "</p>";echo "<p>Your comment: " . e($comment) . "</p>";Always escape all dynamic content - even data from your database.