How can PHP automatically escape special characters in HTML code?
When outputting user-generated content in HTML using PHP, it's important to escape special characters to prevent potential security vulnerabilities like cross-site scripting (XSS) attacks. PHP provides the `htmlspecialchars()` function, which automatically converts special characters like <, >, ", ', and & into their HTML entity equivalents, ensuring that the content is safely displayed in the browser.
<?php
$userInput = "<script>alert('XSS attack!')</script>";
echo htmlspecialchars($userInput, ENT_QUOTES);
?>