How can htmlentities() be used to prevent unwanted input in PHP?

To prevent unwanted input in PHP, you can use the htmlentities() function to convert potentially harmful characters into their HTML entity equivalents. This helps to sanitize user input and prevent cross-site scripting (XSS) attacks by rendering the input harmless when displayed on a webpage.

$input = "<script>alert('XSS attack!')</script>";
$filtered_input = htmlentities($input, ENT_QUOTES, 'UTF-8');
echo $filtered_input;