PHP
Prevent Cross-Site Scripting (XSS) with HTML Output Escaping
Securely display user-generated content on web pages by properly escaping HTML entities, preventing malicious scripts from executing and safeguarding user data.
<?php
// Function to safely output user-supplied text as HTML
function escapeHtml($text) {
return htmlspecialchars($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example user input (malicious)
$userInput = "<script>alert('XSS Attack!');</script><b>Hello</b> & World!";
// Incorrect way (vulnerable to XSS)
// echo $userInput; // This would execute the script
// Correct way (prevents XSS)
$safeOutput = escapeHtml($userInput);
// echo $safeOutput; // Outputs: <script>alert('XSS Attack!');</script><b>Hello</b> & World!
// Example with user data in a template
$username = $_GET['user'] ?? "Guest"; // Imagine this comes from a database or user input
echo "<h1>Welcome, " . escapeHtml($username) . "!</h1>";
echo "<p>Here's your message: " . escapeHtml($userInput) . "</p>";
// If you need to output HTML that is *supposed* to be rendered,
// use a robust HTML sanitization library, NOT just htmlspecialchars.
// e.g., HTML Purifier for PHP or DOMPurify for JavaScript.
?>
How it works: This snippet illustrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by correctly escaping user-generated content before displaying it in HTML. The `htmlspecialchars` function converts special characters like `<`, `>`, `&`, and quotes into their HTML entity equivalents. This ensures that browsers interpret such content as plain text rather than executable code, effectively neutralizing malicious scripts embedded by attackers. For more complex scenarios involving user-allowed HTML, dedicated HTML sanitization libraries are recommended.