2

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?

4
  • AFAIK, that's not built into Blade. You need to use strip_tags to pull out <script> and something like DOMDocument to parse out onload, etc. Commented Nov 5, 2015 at 20:03
  • Have a look at this answer. Commented Nov 5, 2015 at 20:05
  • you need to build your own function to do this. Commented Nov 5, 2015 at 20:06
  • 1
    strip_tags shouldn't be relied upon. He needs something like HTMLpurifier. See my answer. Commented Nov 5, 2015 at 20:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It looks like to be work. But I think there must be something easier.
Updated my answer a bit more to give you more insight.
Thank you very much prograhammer
Have you considered using Markdown instead (like Stackoverflow does)? github.com/GrahamCampbell/Laravel-Markdown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.