What are the risks associated with concatenating variables directly into HTML output, and how can these risks be mitigated in PHP scripts?

Concatenating variables directly into HTML output can make the code vulnerable to XSS (Cross-Site Scripting) attacks, where an attacker can inject malicious scripts into the output. To mitigate this risk, it is recommended to sanitize user input and escape special characters before outputting them to the HTML. This can be achieved using functions like htmlspecialchars() in PHP.

<?php
// Example of mitigating XSS risk by escaping special characters before output
$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput);
echo "<p>User input: $sanitizedInput</p>";
?>