PHP
Securely Escape HTML Output to Prevent XSS Attacks
Learn how to prevent Cross-Site Scripting (XSS) attacks by properly escaping user-generated content before rendering it in HTML, using PHP's `htmlspecialchars` function.
<?php
function secureHtmlOutput(string $input): string {
return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example usage with user-generated content
$userInput = "<script>alert('You are hacked!');</script><h1>User Comment</h1>";
echo "<div>" . secureHtmlOutput($userInput) . "</div>";
// Example with attributes (important to escape them too!)
$userName = "O'Malley" />";
echo "<input type=\"text\" value=\"" . secureHtmlOutput($userName) . "\" />";
// Incorrect (vulnerable) output:
// echo "<div>" . $userInput . "</div>";
?>
How it works: This snippet demonstrates how to prevent Cross-Site Scripting (XSS) vulnerabilities by escaping all user-generated content before displaying it in an HTML context. The `htmlspecialchars` function converts special characters like `<`, `>`, `&`, `"`, and `'` into their HTML entities. Using `ENT_QUOTES` ensures both double and single quotes are escaped, preventing attribute injection. Always apply this to any dynamic content rendered to the browser.