What is the difference between htmlentities() and htmlspecialchars() in PHP when dealing with special characters in HTML code?

When dealing with special characters in HTML code in PHP, htmlentities() and htmlspecialchars() are both used to convert special characters to their HTML entity equivalents 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 &.

// Using htmlspecialchars() to encode special characters in HTML code
$unsafe_string = &#039;&lt;script&gt;alert(&quot;XSS attack!&quot;)&lt;/script&gt;&#039;;
$safe_string = htmlspecialchars($unsafe_string, ENT_QUOTES, &#039;UTF-8&#039;);
echo $safe_string;