How to create middleware for XSS protection in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will i how to create middleware for XSS protection in laravel. XSS(Cross Site Scripting) protection is must need in our site because if we do not XSS protection then our site is not secure. XSS filter through we can remove the html tag from our input value and also it is very important to remove html tag for the security. In our laravel application we can implement it by using middleware concept in our project. So here i will show you how to create XSS filter middleware in our laravel application by using following step.

At first fire following command and need to create middleware:

Create Middleware

php artisan make:middleware XSS

Then now, we can see new file in app/Http/Middleware/XSS.php and then just put the bellow code in our XSS.php file.

XSS.php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class XSS
{
    public function handle(Request $request, Closure $next)
    {
        $input = $request->all();
        array_walk_recursive($input, function(&$input) {
            $input = strip_tags($input);
        });
        $request->merge($input);
        return $next($request);
    }
}

Now at last we have to register our middleware in our app/Http/Kernel.php file. and then add the following line in $routeMiddleware array.

Kernel.php

class Kernel extends HttpKernel
{
	....
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        ....
        'XSS' => \App\Http\Middleware\XSS::class,
    ];
}

So now we are ready to use XSS middleware in our routes.php file, in bellow routes.php file we can do on that way:

routes.php

Route::group(['middleware' => ['XSS']], function () {
  Route::get('customVali', '[email protected]');
  Route::post('customValiPost', '[email protected]');
});

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →