What are the differences between htmlentities() and htmlspecialchars() functions in PHP, and when should each be used?

The main difference between htmlentities() and htmlspecialchars() functions in PHP is that htmlentities() converts all applicable characters to HTML entities, while htmlspecialchars() converts only a few characters (like <, >, ", ', &) to HTML entities. Use htmlentities() when you want to convert all characters to HTML entities to prevent XSS attacks, and use htmlspecialchars() when you only need to convert a few characters for display in HTML.

// Using htmlentities() to convert all characters to HTML entities
$unsafe_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$safe_output = htmlentities($unsafe_input);
echo $safe_output;