What is the purpose of using htmlspecialchars() in PHP and what potential security risks does it mitigate?

When displaying user input on a webpage, it is important to use htmlspecialchars() in PHP to prevent cross-site scripting (XSS) attacks. This function converts special characters like < and > into their HTML entities, ensuring that the input is displayed as text and not executed as code. By using htmlspecialchars(), you can protect your website from malicious scripts that could be injected through user input.

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