What is the purpose of using htmlentities() in the PHP code provided?
The purpose of using htmlentities() in PHP code is to convert potentially harmful characters into their HTML entity equivalents, making the output safe to display on a webpage and preventing XSS (Cross-Site Scripting) attacks. This function helps to sanitize user input before displaying it on the website, ensuring that any malicious code is not executed.
// Original PHP code with user input
$user_input = "<script>alert('XSS attack!')</script>";
// Using htmlentities() to sanitize user input
$safe_input = htmlentities($user_input);
// Display the sanitized input
echo $safe_input;