PHP
Server-Side HTML Encoding for Cross-Site Scripting (XSS) Prevention
Prevent Cross-Site Scripting (XSS) vulnerabilities in PHP by using `htmlspecialchars()` to safely encode user-generated content before rendering it in HTML, neutralizing malicious scripts.
<?php
function display_comment($comment_text) {
// Simulate fetching user comment from a database
// In a real application, $comment_text would come from user input
$raw_comment = $comment_text;
// Sanitize output using htmlspecialchars() to prevent XSS
// ENT_QUOTES encodes both single and double quotes
// 'UTF-8' specifies the character encoding
$safe_comment = htmlspecialchars($raw_comment, ENT_QUOTES | ENT_HTML5, 'UTF-8');
echo "<div class='comment-box'>
";
echo " <p>" . $safe_comment . "</p>
";
echo "</div>
";
}
// Example of malicious input
$user_input_malicious = "<script>alert('You have been hacked!');</script>This is a comment.";
// Example of benign input
$user_input_benign = "This comment contains <b>bold</b> text and special characters like < & >.";
echo "<h2>Displaying Malicious Comment (Sanitized):</h2>";
display_comment($user_input_malicious);
echo "<h2>Displaying Benign Comment (Sanitized):</h2>";
display_comment($user_input_benign);
?>
How it works: This PHP snippet demonstrates a fundamental server-side approach to preventing Cross-Site Scripting (XSS) attacks: output encoding. When displaying user-generated content on a web page, it's crucial to escape any characters that could be interpreted as HTML tags or script code. The `htmlspecialchars()` function converts special characters like `<`, `>`, `&`, and quotes into their HTML entities (e.g., `<` becomes `<`). This renders potentially malicious scripts harmless by making them display as text rather than executing as code, ensuring the integrity of your web page.