Skip to content
PHP Logo

How can HTML escaping be implemented in PHP to prevent XSS vulnerabilities when outputting user-generated content?

To prevent XSS vulnerabilities when outputting user-generated content in PHP, HTML escaping can be implemented by using the htmlspecialchars() function. This function converts special characters like <, >, ", ', and & into their HTML entities, preventing them from being interpreted as HTML code.

php
$userInput = "<script>alert('XSS attack!')</script>";
$escapedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $escapedInput;