How can the use of htmlentities() function improve the handling of special characters in PHP code?

Special characters in user input can cause security vulnerabilities like cross-site scripting (XSS) attacks in PHP code. By using the htmlentities() function, special characters are converted into their corresponding HTML entities, preventing them from being interpreted as code and ensuring that user input is safely displayed on a webpage.

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