ozmnow's avatar

Is it safe to use {!!nl2br(e())!!} in blade

In order to output text in Laravel blade templates with new lines I use this:

{!! nl2br(e($prodData->text))!!}

I do not do not sanetize the data when I insert it, I just trim it to only allow two new lines in a row like this:

public function setDescriptionAttribute($description)
  {
      $this->attributes['description'] = preg_replace('~(\R{2})\R+~', '', $description);
  }

But now I am worried that {!!nl2br(e())!!} can cause xss injections so is it safe to use?

0 likes
5 replies
ozmnow's avatar

@rin4ik should I always use e() in blade or can I simply use double {{ $myVar }} in cases where I only need to output a string and not use stuff like nl2br()

rin4ik's avatar

yes only when you want to use nl2br(). this is {{}} safe

Cronix's avatar

If you want to use nl2br(), you have to use {!! $var !!}, since nl2br() will return html (<br> tags). Otherwise it will print <br> instead of actually breaking.

dotancohen's avatar

I often use variations on this theme:

@php
    $paragraphs = explode("\n", $content);
    $firstPass = true;
    foreach ($paragraphs as $paragraph) {
        if ( !$firstPass) {
            echo "<br />";
        }
        echo e($paragraph);
    }
@endphp

In plain text the newline character is often used to signify not necessarily a semantic new line, but rather paragraphs. Thus this is a common variation that I use:

@php
    $paragraphs = explode("\n", $content);
    foreach ($paragraphs as $paragraph) {
        $paragraph = trim($paragraph);
        echo $paragraph ? "<p>".e($paragraph)."</p>" : "<p>&nbsp;</p>";
    }
@endphp

Don't forget to normalize line endings from \r\n and \r if that may be a concern with your use case.

1 like

Please or to participate in this conversation.