What is the difference between htmlspecialchars() and htmlentities() in PHP?

The main difference between htmlspecialchars() and htmlentities() in PHP is how they handle characters. htmlspecialchars() only converts the predefined characters (<, >, ", ', &) into their respective HTML entities, while htmlentities() converts all applicable characters to HTML entities. If you want to convert all characters to HTML entities for security purposes, htmlentities() is the better choice. However, if you only want to convert a few characters to prevent XSS attacks, htmlspecialchars() is sufficient.

// Using htmlspecialchars() to convert specific characters to HTML entities
$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;