How can XSS vulnerabilities be prevented in PHP forms, especially when handling user input?

XSS vulnerabilities in PHP forms can be prevented by properly sanitizing and validating user input before displaying it on the webpage. This can be done by using functions like htmlspecialchars() to encode special characters, or by implementing input validation to ensure that only expected data types are accepted.

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

// Validate user input to only accept certain data types
if (is_numeric($user_input)) {
    // Process the input if it is a valid number
} else {
    // Display an error message or reject the input
}