What are common pitfalls to avoid when working with nl2br in PHP for text formatting?
One common pitfall when working with nl2br in PHP is forgetting to escape HTML entities before applying nl2br to prevent potential XSS attacks. To avoid this issue, always use htmlspecialchars() before using nl2br on user-generated content.
$userInput = "<script>alert('XSS attack');</script>\nNew line";
$escapedInput = htmlspecialchars($userInput);
$formattedText = nl2br($escapedInput);
echo $formattedText;
Keywords
Related Questions
- What is the correct way to include an external CSS file in a PHP file?
- What are the potential consequences of overlooking simple syntax rules in PHP, such as using semicolons instead of commas in array elements?
- What considerations should be taken into account when normalizing database tables for a PHP project like this?