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);
?>
Related Questions
- What common syntax errors should PHP developers be aware of when writing functions in PHP?
- What are some best practices for implementing links to navigate to the next and previous news articles in a PHP news system?
- How can I ensure that the displayed prices in the PayPal window reflect gross prices instead of net prices?