PHP
Secure HTML Output with PHP's htmlentities
Learn to prevent Cross-Site Scripting (XSS) attacks by properly escaping user-generated content for safe display in HTML using PHP's htmlentities function.
<?php
// Simulate user input
$user_comment = "<script>alert('XSS Attack!');</script> Hello, World! <b>Bold Text</b>";
// Sanitize user input before displaying it in HTML
// ENT_QUOTES: Converts both double and single quotes
// 'UTF-8': Specifies the character encoding
$safe_comment = htmlentities($user_comment, ENT_QUOTES, 'UTF-8');
echo "<h3>Original Comment:</h3>";
echo $user_comment; // Potentially unsafe output
echo "<h3>Sanitized Comment:</h3>";
echo $safe_comment; // Safe output
// Example in a typical web context (e.g., displaying a user-submitted comment)
function displaySafeOutput($input) {
return htmlentities($input, ENT_QUOTES, 'UTF-8');
}
$blog_post_title = "My Latest Post <script>stealCookies();</script>";
echo "<h1>" . displaySafeOutput($blog_post_title) . "</h1>";
?>
How it works: This snippet demonstrates how to prevent Cross-Site Scripting (XSS) attacks by using PHP's `htmlentities()` function. `htmlentities()` converts all applicable characters to HTML entities, making them safe to display in a web browser. The `ENT_QUOTES` flag ensures both single and double quotes are converted, and `UTF-8` specifies the character encoding, which is crucial for handling international characters correctly. Always sanitize user-generated content right before outputting it to the browser.