Skip to content
PHP Logo

What potential issues can arise when using nl2br() function in PHP to handle line breaks in textareas?

The nl2br() function in PHP can potentially introduce security vulnerabilities such as Cross-Site Scripting (XSS) attacks if user input is not properly sanitized. To prevent this, it is important to use htmlspecialchars() function to escape special characters before passing the input to nl2br(). This will ensure that any malicious scripts are not executed when the text is displayed on the webpage.

php
// Sanitize user input before using nl2br()
$text = htmlspecialchars($_POST['textarea_input']);
$text_with_line_breaks = nl2br($text);

echo $text_with_line_breaks;