How does using htmlentities() function help in ensuring security when outputting user input?

When outputting user input directly onto a webpage, it is important to sanitize the input to prevent cross-site scripting (XSS) attacks. Using the htmlentities() function in PHP helps encode special characters in the user input, such as <, >, ", ', and &, into their respective HTML entities. This ensures that the user input is displayed as plain text on the webpage, preventing any malicious scripts from being executed.

$userInput = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
echo htmlentities($userInput);