Laravel 5 XSS Middleware

Submitted by kirkbushell - 4 years ago

This piece of middleware can be applied at a global level, or on a per-route basis. The idea is that instead of polluting your databases with HTML and other potentially damaging data as a result of user input, this middleware will immediately strip all tags from any input, before it gets to validation or saved to a database. The result? A more dependable solution that doesn't require developer memory to implement safe output rules + cleaner data in your database.

class XSSProtection
{
    /**
     * The following method loops through all request input and strips out all tags from
     * the request. This to ensure that users are unable to set ANY HTML within the form
     * submissions, but also cleans up input.
     *
     * @param Request $request
     * @param callable $next
     * @return mixed
     */
    public function handle(Request $request, \Closure $next)
    {
        if (!in_array(strtolower($request->method()), ['put', 'post'])) {
            return $next($request);
        }

        $input = $request->all();

        array_walk_recursive($input, function(&$input) {
            $input = strip_tags($input);
        });

        $request->merge($input);

        return $next($request);
    }
}
comments powered by Disqus