How to create middleware for XSS protection in laravel 5?

By Hardik Savani | March 4, 2016 | | 2740 Viewer | Category : PHP Laravel


Share this post:

XSS(Cross Site Scripting) protection must need in your site because if you do not XSS protection then your site is not secure. XSS filter through you can remove html tag from your input value and it is very important to remove html tag for security. in your laravel 5.2 application you can implement by using middleware concept in your project. so how to create XSS filter middleware in your laravel application by using following step.

First fire following command and create middleware:

Create Middleware

php artisan make:middleware XSS

Now, you can see new file in app/Http/Middleware/XSS.php and just put bellow code in your 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);

}

}

At last you have to register your middleware in your app/Http/Kernel.php file. and add 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,

];

}

Now you are ready to use XSS middleware in your routes.php file, in bellow routes.php file you can that way:

routes.php

Route::group(['middleware' => ['XSS']], function () {

Route::get('customVali', 'CustomValDemoController@customVali');

Route::post('customValiPost', 'CustomValDemoController@customValiPost');

});