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

The main difference between htmlspecialchars() and htmlentities() in PHP is that htmlspecialchars() only converts predefined characters (like < and >) to their HTML entities, while htmlentities() converts all applicable characters to HTML entities. If you want to encode user input to prevent XSS attacks, it is generally recommended to use htmlspecialchars().

// Using htmlspecialchars() to encode user input
$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack&#039;)&lt;/script&gt;&quot;;
$encoded_input = htmlspecialchars($user_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo $encoded_input;