What are the differences between htmlentities() and htmlspecialchars() functions in PHP?

htmlentities() and htmlspecialchars() are both PHP functions used to convert special characters to HTML entities to prevent XSS attacks. The main difference between the two functions is that htmlentities() converts all applicable characters to HTML entities, while htmlspecialchars() only converts characters that have special meaning in HTML (such as <, >, ", ', and &). In most cases, it is recommended to use htmlspecialchars() as it provides sufficient protection against XSS attacks without over-encoding the output.

// Using htmlspecialchars() to escape special characters in a string
$string = &quot;&lt;script&gt;alert(&#039;XSS attack&#039;);&lt;/script&gt;&quot;;
echo htmlspecialchars($string, ENT_QUOTES, &#039;UTF-8&#039;);