shold i use htmlspecialchars in laravel at input?

63 Views Asked by At

In Laravel 10 i have a userController with a function like this:

public function login(Request $request){    
    
    $userInputs = $request->validate([
        'username' => ['required', 'max:100', 'exists:users,username'],
    ]);

    //more code ....
}

but i noticed with this users can bring things like this in the database:

<script> alert("hacked"); </script>

this is not further problematic since blade escapes the input with the htmlspecialchars function with the {{ }}.

But i don't like the idea that there is something bad in may database. Maybe i need to debug something later in my app and i forget about that.

So i tried to implement the htmlspecialchars function into my code. But, when i use it after the validate function where it checks if the username exists in the database 'exists:users,username' and then save it in the database the 'exists:users,username' function would not work anymore.

But implementation in validation is not planned. But it would need to be executed before the validation. I also would like to have all the validation in the validation function and not something that i would have to write before.

How would you do that? Or would you even use the htmlspecialchars function before you save it to the database?

1

There are 1 best solutions below

0
aynber On

You can use a FormRequest to validate your login, and also use it to convert the username before it's validated. You would create the FormRequest as shown in the documentation, then add this function to the FormRequest:

protected function prepareForValidation()
{
    $this->merge([
        // We are exploding the role field from `role-1` to `role` and `1`
        'username' => htmlspecialchars($this->username)
    ]);
}