What is the function htmlentities() in PHP and how can it be used to prevent issues with displaying data?

When displaying user input on a webpage, it is important to sanitize the data 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, preventing malicious scripts from being executed in the browser.

// Example of using htmlentities() to prevent XSS attacks
$user_input = "<script>alert('XSS attack!');</script>";
$sanitized_input = htmlentities($user_input);

echo $sanitized_input;