PHP
Securely Output User Input to Prevent XSS
Learn to prevent Cross-Site Scripting (XSS) attacks by securely encoding user-generated data before rendering it in HTML, using PHP's htmlspecialchars.
<?php
function secureOutput($data) {
return htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// Example usage:
$userComment = "<script>alert('XSS Attack!');</script> Your comment here.";
$userName = "John Doe <img src='x' onerror='alert(\"XSS!\")'>";
echo "<h3>User Comment:</h3>";
echo "<p>" . secureOutput($userComment) . "</p>";
echo "<h3>User Name:</h3>";
echo "<span>" . secureOutput($userName) . "</span>";
// Expected output for demonstration (HTML encoded):
// <h3>User Comment:</h3><p><script>alert('XSS Attack!');</script> Your comment here.</p>
// <h3>User Name:</h3><span>John Doe <img src='x' onerror='alert("XSS!")'></span>
?>
How it works: This snippet demonstrates how to prevent Cross-Site Scripting (XSS) by encoding special characters in user-generated input before displaying it in HTML. The `htmlspecialchars` function in PHP converts characters like `<`, `>`, `&`, `"`, and `'` into their corresponding HTML entities. This ensures that the browser interprets the input as plain text rather than executable code, effectively neutralizing XSS attempts. The `ENT_QUOTES | ENT_HTML5` flags ensure both single and double quotes are handled and uses the HTML5 doctype.