DEV Community

Basim Ghouri
Basim Ghouri

Posted on • Updated on

Security in Laravel: How to Protect Your App Part 2

XSS Attack

This attack could be divided into two sections. The first one restricts special tags on the server and does not return special tags in the views.

Restrict Special Tags in the Server

You could use different approaches. PHP natively has some methods like strip_tags that only protect against HTML and PHP tags. You can even use a regex or use the PHP native method htmlentities() or filter_var both, although it does not protect completely against all the possible tags. In this case, my best recommendation is to use a specific package to solve this, like

HTML Purifier.

Does Not Return Special Tags in the Views
If you are working with the Blade template engine, you should take care about how you are printing your data in your template:

<p>{{ $user->name }}</p>
Enter fullscreen mode Exit fullscreen mode

The double mustaches syntax would protect you against XSS attacks by automatically escaping the tags for you.

<p>{!! $user->name !!}</p>
Enter fullscreen mode Exit fullscreen mode

On the other hand, this syntax is dangerous. If you do not trust the data that could come, do not use it because the bang-bang syntax could interpret PHP.

Using Another PHP Template Engine

Laravel also provides an escape method that we use on any other template engine like Twig:

{{ e($user->name) }}
Enter fullscreen mode Exit fullscreen mode

Using a Javascript Framework

Any modern Javascript framework automatically protects us to inject a script. VueJS, for example, has a v-html directive that already protects us against this type of attack.

Top comments (1)

basimghouri profile image
Basim Ghouri

Follow And like for more laravel security parts