What is the function of htmlentities() in PHP and how can it be used in this context?

The htmlentities() function in PHP is used to convert special characters to HTML entities. This is useful when displaying user input on a webpage to prevent cross-site scripting attacks. By using htmlentities(), special characters like <, >, and & are converted to their corresponding HTML entities, ensuring that they are displayed as text rather than interpreted as HTML code.

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