In the context of PHP programming, what are the differences between htmlentities and htmlspecialchars functions, and when should each be used?

The main difference between htmlentities and htmlspecialchars functions in PHP is how they handle special characters. htmlentities will convert all applicable characters to HTML entities, while htmlspecialchars will only convert characters that are special in HTML. It is generally recommended to use htmlspecialchars when outputting user input to prevent XSS attacks, as it only escapes characters that have special meaning in HTML.

// Using htmlspecialchars to escape user input before outputting it
$userInput = "<script>alert('XSS attack');</script>";
echo htmlspecialchars($userInput, ENT_QUOTES);