How can the use of htmlspecialchars() function in PHP prevent security vulnerabilities when outputting data in HTML?
When outputting data in HTML, using the htmlspecialchars() function in PHP helps prevent security vulnerabilities such as cross-site scripting (XSS) attacks. This function converts special characters like <, >, ", ', and & into their HTML entities, ensuring that user input is displayed as text rather than interpreted as HTML code by the browser.
<?php
// Data to be outputted in HTML
$userInput = "<script>alert('XSS attack!');</script>";
// Using htmlspecialchars() to prevent XSS attacks
echo htmlspecialchars($userInput);
?>