How can the htmlspecialchars() function be utilized to prevent security vulnerabilities in PHP-generated HTML code?
The htmlspecialchars() function in PHP can be utilized to prevent security vulnerabilities such as cross-site scripting (XSS) attacks by converting special characters like < and > into their HTML entities. This ensures that user input is displayed as text on the webpage rather than being interpreted as HTML code, thus preventing malicious scripts from being executed.
$user_input = "<script>alert('XSS attack!');</script>";
$safe_input = htmlspecialchars($user_input);
echo $safe_input;