How can the use of htmlspecialchars function prevent XSS attacks when outputting user input in HTML code generated by PHP scripts?

XSS attacks occur when user input is not properly sanitized and is directly outputted in HTML code, allowing malicious scripts to be executed. Using the htmlspecialchars function in PHP converts special characters to HTML entities, preventing the execution of scripts embedded in user input.

// Example PHP code snippet using htmlspecialchars to prevent XSS attacks
$user_input = "<script>alert('XSS attack!');</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "<p>User input: $escaped_input</p>";