In what situations would it be necessary to use htmlentities() instead of htmlspecialchars() in PHP and what are the differences between the two functions?

When dealing with user input that may contain special characters, it is important to sanitize the input to prevent XSS attacks. The htmlentities() function in PHP converts all applicable characters to HTML entities, while htmlspecialchars() only converts characters that have special meaning in HTML. If you need to encode all characters, including non-ASCII characters, then htmlentities() should be used.

$user_input = "<script>alert('XSS attack');</script>";
$encoded_input = htmlentities($user_input);
echo $encoded_input;