Home > Backend Development > PHP Tutorial > How to create middleware for XSS defense in laravel 5?

How to create middleware for XSS defense in laravel 5?

藏色散人
Release: 2023-04-05 13:20:01
Original
3624 people have browsed it


XSS filters can remove html tags from input values, so it is important to remove html tags for security reasons. In laravel 5.2 this can be achieved by using middleware concept in your project.

How to create middleware for XSS defense in laravel 5?

Now I will introduce to you how to create XSS filtering middleware in laravel application.

First launch the following command and create the middleware:

Create middleware

php artisan make:middleware XSS
Copy after login

Now, you can create the middleware in app/Http/Middleware /XSS.php and place the following code into 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);
    }
}
Copy after login

Finally, the middleware must be registered in the app/Http/Kernel.php file. And add the following lines in the $routeMiddleware array.

Kernel.php

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

Now you can use XSS middleware in your routing .php file. In the following routing .php file you can do this :

routes.php

Route::group(['middleware' => ['XSS']], function () {
  Route::get('customVali', 'CustomValDemoController@customVali');
  Route::post('customValiPost', 'CustomValDemoController@customValiPost');
});
Copy after login

Related laravel video tutorial: "Latest laravel mall practical video tutorial"

Related blog Recommended: "Defense against SQL Injection and XSS Attacks"

This article is an introduction to the method of creating middleware for XSS defense in laravel 5. I hope it will be useful to friends who need it. help!


The above is the detailed content of How to create middleware for XSS defense in laravel 5?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template