Mike Rifgin
Mike Rifgin

Reputation: 10745

input sanitization VS validation

I've implemented input validation on all of my input data using php (as well as js on the front-end). I'm type casting where I can, validating stuff like emails against a regex, making sure dropdown values are only ones I'm expecting and also in many cases where I'm expecting only a string I have a regex that runs that only allows letters, numbers and spaces. Anything that doesn't meet these rules results in the form failing validation and no sql queries are run.

With that said if my form passes validation I'm making the assumption that it's safe for input in to my db (which I'm doing via pdo) and then escaped on output.

So with that said why do I need input sanitization?

Upvotes: 11

Views: 4037

Answers (2)

Arend
Arend

Reputation: 3761

If you have very strict validation server-side, you don't need to sanatize. Eg. validating a string against /^[a-z0-9]{5,25}$/ will not need any sanitization (removing non alphanumeric characters will not make any sense, since they should not be able to pass anyway).

Just make sure you can validate all data, and if that's impossible (e.g. with html it tends to be a bit difficult), you can use escaping strategies or things like html purifier.

For a good overview on escaping strategies for XSS prevention: see https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

For an idea of different security threats: https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet

Upvotes: 8

Grim...
Grim...

Reputation: 16953

You need both. Validating input data is easily beaten at the client side, but it's useful for legitimate users who aren't trying to hack you. Sanitize the data (all the data, whether it's input data or something straight from your DB that you think you should be able to trust) before putting it into your database.

Even if you 100% trust your validation and do it on the server side (where, in theory, people shouldn't be able to mess with the data), it's still worth using some form of sanitizing because it's a good habit to get into.

Upvotes: 4

Related Questions