Farid Movsumov
Farid Movsumov

Reputation: 12735

Laravel5 - How to render only html tags not javascript in Blade?

I want to render user input $content as HTML but prevent JavaScript to be executed (for preventing XSS attacks) ın blade template engine. Following code renders both HTML and JavaScript.

{!! $content !!}

How can I do that?

Upvotes: 2

Views: 1918

Answers (1)

prograhammer
prograhammer

Reputation: 20630

There's nothing built into Blade to do this. It gives you the {!! !!} option so you can do your own cleaning when necessary. If you want your HTML to work, but prevent Javascript, then you will need to do some work to specially purify it. Here's a package that implements the popular HTMLpurifier in Laravel 5:

https://github.com/etcinit/purifier

You can see that by its default configuration it uses a whitelist to ensure javascript doesn't pass through:

src/Chromabits/Purifier/Purifier.php

protected function getDefaultConfig()
{
        return [
            'HTML.Doctype' => 'XHTML 1.0 Strict',
            'HTML.Allowed' => 'div,b,strong,i,em,a[href|title],ul,ol,li'
                . ',p[style],br,span[style],img[width|height|alt|src]',
            'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style'
                . ',font-family,text-decoration,padding-left,color'
                . ',background-color,text-align',
            'AutoFormat.AutoParagraph' => true,
            'AutoFormat.RemoveEmpty' => true,
        ];
}

Use it in your controller like:

public function getIndex(Request $request)
{
    return $this->purifier->clean($request->input('first_name'));
}

The other alternative would be to not allow your users to input direct HTML but perhaps instead use something like Markdown. This is what StackOverFlow does.

Upvotes: 2

Related Questions