What is the significance of using htmlentities() function in PHP when dealing with special characters in user input?

When dealing with user input that contains special characters, it is important to sanitize the input to prevent potential security vulnerabilities such as cross-site scripting (XSS) attacks. The htmlentities() function in PHP converts special characters to their corresponding HTML entities, ensuring that the input is displayed as intended on the webpage without being interpreted as code.

$user_input = "<script>alert('Hello!');</script>";
$sanitized_input = htmlentities($user_input);
echo $sanitized_input;