What are some potential security risks associated with using the htmlentities function in PHP scripts for search functionality?

Using the htmlentities function in PHP scripts for search functionality can potentially lead to security risks such as Cross-Site Scripting (XSS) attacks. To mitigate this risk, it is recommended to use the htmlspecialchars function instead, as it only converts the predefined characters like < and > to their HTML entities, leaving other characters intact.

$search_query = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
$safe_query = htmlspecialchars($search_query, ENT_QUOTES, &#039;UTF-8&#039;);
echo &quot;Safe search query: &quot; . $safe_query;