PHP
Server-Side HTML Encoding to Prevent XSS on Display
Prevent Cross-Site Scripting (XSS) attacks by properly HTML encoding user-generated content on the server-side before displaying it in your PHP web application.
<?php
/**
* Safely outputs user-generated content by HTML encoding it.
* This function should be used whenever displaying user input on a web page.
* @param string $input The string to be HTML encoded.
* @return string The HTML encoded string.
*/
function safe_html_output($input) {
// ENT_QUOTES encodes both single and double quotes.
// 'UTF-8' specifies the character encoding.
return htmlspecialchars($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example of malicious input
$userInput = "<script>alert('You are hacked!');</script>User Name & 'Co.'";
$userComment = "I love this product! <img src='x' onerror='alert(\"XSS\")'>";
// Displaying the encoded content
echo "<p>Encoded User Input: " . safe_html_output($userInput) . "</p>
";
echo "<p>Encoded User Comment: " . safe_html_output($userComment) . "</p>
";
echo "
<!-- Raw output for comparison (DO NOT DO THIS IN PRODUCTION!) -->
";
echo "<p>Raw User Input (UNSAFE): " . $userInput . "</p>
";
?>
How it works: Cross-Site Scripting (XSS) is a common vulnerability where attackers inject malicious scripts into web pages viewed by other users. A crucial server-side defense mechanism is HTML encoding user-generated content right before it's displayed on a web page. This PHP snippet demonstrates using the `htmlspecialchars()` function for this purpose. `htmlspecialchars()` converts special HTML characters (like `<`, `>`, `&`, `'`, `"`) into their HTML entities (e.g., `<` becomes `<`), rendering them harmless text instead of executable code. By using `ENT_QUOTES`, both single and double quotes are encoded, preventing attribute-based XSS. Always encode user input at the point of output, not just at input, to prevent context-dependent XSS attacks.