What are the recommended methods for handling user input in PHP forms to prevent cross-site scripting (XSS) attacks?

To prevent cross-site scripting (XSS) attacks in PHP forms, it is recommended to sanitize and validate user input before processing it. This can be done by using functions like htmlspecialchars() to escape special characters and prevent malicious scripts from being executed.

// Sanitize user input to prevent XSS attacks
$user_input = htmlspecialchars($_POST['user_input']);

// Validate and process sanitized input
if(isset($user_input)) {
    // Process the sanitized input
}