What are the best practices for handling user input and displaying messages to prevent XSS attacks in PHP?

To prevent XSS attacks in PHP, it is important to properly sanitize and validate user input before displaying it on the webpage. This can be done by using functions like htmlspecialchars() to encode special characters and prevent script injection. Additionally, it is recommended to use prepared statements when interacting with databases to prevent SQL injection attacks.

// Sanitize user input using htmlspecialchars()
$userInput = htmlspecialchars($_POST['input']);

// Display the sanitized input
echo $userInput;