How can PHP beginners effectively handle user input to prevent XSS attacks?

To prevent XSS attacks in PHP, beginners can effectively handle user input by using the htmlentities() function to encode user input before displaying it on the webpage. This function converts special characters to their HTML entities, preventing them from being interpreted as code by the browser.

$user_input = "<script>alert('XSS attack!');</script>";
$encoded_input = htmlentities($user_input);
echo $encoded_input;