Laravel XSS Input Sanitization

Why do we need Input Sanitization?

Hackers use RFI (Remote File Inclusion) and injection attacks like Cross-Site Script (XSS) and SQL Injection (SQLi) to exploit the connection between websites and servers. They can execute unauthorized actions that can compromise security. However, with sanitization in place, these attacks can be prevented.

  • Preventing remote file inclusion and injection attacks
  • Protecting the system from malicious code
  • Safeguarding the web server, database, and other digital assets

Possible XSS Exploitation Points

There are different ways a hacker can attack your Laravel web application. The following are a few examples to look out for:

Script in Attributes

XSS attacks may be conducted without using the <script>…</script> tags. Other tags will do exactly the same thing, such as <body onload=alert(‘test1’)> or other attributes including onmouseover or onerror.

  1. <b onmouseover=alert(‘Wufff!’)>click me!</b>
  2. onerror
  3. <img src=”" onerror=alert(document.cookie);>

Script Via Encoded URI Schemes

If we need to hide against web application filters, we may try to encode string characters, e.g.: a=&\#X41 (UTF-8) and use it in IMG tags:

Code Encoding

We can encode our scripts in base64 and place them in the Meta Tag. This way we get rid of alert() completely.

  1. CONTENT=”0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg”>

Laravel Validation Rules Provided by Default

  • required: Only accept if the value is not null. Laravel nulls the input if the field is left empty.
  • email: Only accept if the input is in email format,
  • sometimes: A web-form field that might be there because of a selected option in the form. In that case, you can specify sometimes | required

Laravel Sanitization

Sanitization of input includes the techniques to identify and remove the possible input entries of strings that can be harmful to your application.

  1. $cleaned_name = strip_tags($request->input(‘name’));
  2. $task = new Task;
  3. $task->names = $cleaned_name;
  4. $task->save();
  5. return redirect(‘/’);

How to Add Middleware for Validation Checks on User Input

Let’s have a look at adding the authorization and validation at the same time on web forms. Laravel offers a Request class for this purpose.

  1. use Closure;
  2. use Illuminate\Http\Request;
  3. class XssSanitizer
  4. {
  5. public function handle(Request $request, Closure $next)
  6. {
  7. $input = $request->all();
  8. array_walk_recursive($input, function(&$input) {
  9. $input = strip_tags($input);
  10. });
  11. $request->merge($input);
  12. return $next($request);
  13. }
  14. }
  1. {
  2. ….
  3. protected $routeMiddleware = [
  4. ‘auth’ => \App\Http\Middleware\Authenticate::class,
  5. ….
  6. ‘XssSanitizer’ => \App\Http\Middleware\XssSanitizer::class,
  7. ];
  8. }
  9. You can now use the XssSanitization middleware in the routes.
  10. Route::group([‘middleware’ => [‘XssSanitizer’]], function () {
  11. Route::get(‘view-register’, ‘RegisterController@viewRegisterPage’);
  12. Route::post(‘register’, ‘RegisterController@registerAction);
  13. });

Best Practices for XSS Protection in a Laravel Application

Here are some key takeaways for the best application of this procedure.

  • Do not overlook client-side validation. This tutorial was focused on backend validation, but you could easily add a new layer of front-end protection using HTML/JavaScript. For example, I can limit the input length through HTML:
    <input type=”text” name=”task” maxlength=”10″>
  • Alternatively, I could have used a JS function to validate/sanitize the input.
    function validateForm() {
    var x = document.forms[“myTasksForm”][“task”].value;
    if (x == null || x == “” || x.length > 10) {
    alert(“Task must not be empty and must be shorter than 10 characters”);
    return false;
  • Encoding URLs to deny access to the Get parameters.
  • By using an Auto-Escaping Template System such as Laravel Blade Templates.
  • By using libraries that are specifically designed to sanitize HTML input:
  • PHP Html Purifier
  • .Net HTML sanitizer (“The library is unit tested with the OWASP XSS Filter Evasion Cheat Sheet“)
  • OWASP Java HTML Sanitizer
  • Python Bleach
  • For an in-depth and updated list of practices, check out The Open Web Application Security Project (OWASP).
  • Standardization at the header level of Content-Type and make sure that the response type of the server isn’t “text / html” and prevent the browser from auto-detecting the data type ‘nosniff’.
  • Implement a Content Security Policy (CSP) to limit the negative consequences when malicious code is inserted.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store