Skip to content

Instantly share code, notes, and snippets.

@kirkbushell
Last active November 5, 2021 06:08
Show Gist options
  • Save kirkbushell/5d40fdd7f7b364716742 to your computer and use it in GitHub Desktop.
Save kirkbushell/5d40fdd7f7b364716742 to your computer and use it in GitHub Desktop.
Laravel 5 XSS protection middleware
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);
}
}
@cinkagan
Copy link

Hi. I introduced an arrangement that removes all special characters.

<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Redirect;
use Closure;

class XSS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $url = str_replace($request->url(), "", $request->fullUrl());
        $input = $request->all();

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

        if (preg_match('/[\'^£$%&*()}{@#~><>|_+¬-]/', $url))
            return redirect($request->url() . "/" . preg_replace('/[\'^£$%&*()}{@#~><>|_+¬-]/',"",strip_tags($url)));

        $request->merge($input);
        return $next($request);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment