What are the differences between using htmlspecialchars() and htmlentities() to escape special characters in PHP?

When dealing with user input in PHP, it's important to escape special characters to prevent XSS attacks. Both htmlspecialchars() and htmlentities() can be used for this purpose, but there are some differences between the two functions. htmlspecialchars() only converts the predefined characters '<', '>', '&', '"', and ''' to their HTML entities, while htmlentities() converts all applicable characters to their HTML entities. If you only need to escape these predefined characters, htmlspecialchars() is more efficient. However, if you want to escape all characters, htmlentities() is the safer option.

// Using htmlspecialchars()
$unsafe_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_output = htmlspecialchars($unsafe_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo $safe_output;