PHP
Prevent Cross-Site Scripting (XSS) with PHP Output Encoding
Learn to prevent XSS vulnerabilities in PHP by using `htmlspecialchars()` to safely encode user-generated content before rendering it in HTML, neutralizing malicious scripts.
<?php
// Simulate user-generated content from a database or form submission
$userName = "<script>alert('You are hacked!');</script>John Doe";
$comment = "This is a comment with <b>bold text</b> and also some <a href='javascript:alert(\"Malicious link!\")'>bad stuff</a>.";
$rawInput = "<h1>Not Encoded Heading</h1><p>Malicious content: <script>alert('XSS!');</script></p>";
echo "<h2>Safely Displaying User Name:</h2>";
echo "<p>" . htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') . "</p>";
echo "<h2>Safely Displaying User Comment:</h2>";
// For comments, you might want to allow some HTML, but sanitize it thoroughly
// For demonstration, we'll just encode everything
echo "<p>" . htmlspecialchars($comment, ENT_QUOTES, 'UTF-8') . "</p>";
echo "<h2>Displaying Raw Input (DANGEROUS - DO NOT DO THIS IN PRODUCTION):</h2>";
echo $rawInput; // This is vulnerable to XSS!
echo "<h2>Safely Displaying Raw Input:</h2>";
echo htmlspecialchars($rawInput, ENT_QUOTES, 'UTF-8');
?>
How it works: This PHP snippet illustrates how to prevent Cross-Site Scripting (XSS) attacks by properly encoding user-generated content before displaying it in an HTML context. The `htmlspecialchars()` function converts special characters like `<`, `>`, `&`, `"`, and `'` into their HTML entities. This neutralizes any embedded script tags or malicious HTML, ensuring that the browser renders them as plain text rather than executing them as code, thereby protecting users from XSS vulnerabilities.