What are the potential pitfalls of directly writing user input into HTML files using PHP?

Directly writing user input into HTML files using PHP can lead to security vulnerabilities such as cross-site scripting (XSS) attacks. To prevent this, user input should be properly sanitized and escaped before being outputted to the HTML file. This can be done using functions like htmlspecialchars() or htmlentities() to encode special characters and prevent malicious scripts from being executed.

$userInput = "<script>alert('XSS attack!');</script>";
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo "<p>User input: $sanitizedInput</p>";