Where to sanitize user input

Should we sanitize the $_POST and $_GET once we want the values?
Or, should we just sanitize it on the template ?
Should we keep bare user input in the database, or the sanitized one ?

You should validate the user input rather than sanitize it. That way the user gets the chance to fix their error.

Any inputs that you sanitize should normally be the same afterward as they were before - only if someone has tampered with the data would sanitizing make any changes to the data.

You should only ever save untainted data in the database (data that was validated or sanitized immediately on input). You should move the data out of the tainted $_POST and $_GET arrays when you validate/sanitise it so that you know that it is now untainted (as tainted vs untainted fields are most readily identified by their field names)

1 Like

Since templates end up in the client’s browser as HTML(also, in most cases, along with some form of JS), and since code in the browser can be manipulated relatively easily (including JS), it makes no sense to “only” do filtering (sanitizing and validating) on the client side. That being said, it doesn’t hurt either, especially when creating a modern website to improve the user experience.

However, being it is “user input” we are talking about, it should always be sanitized on the server-side too, and as soon as possible, like when the input first hits the server. Or, at the latest, before it can do any damage. Validation, on the other hand, should be part of your model, so validation should happen some time just before input data is needed to make any logical decisions and/ or before it is persisted.

Scott

1 Like

Using prepared statements in regards to a database will 99 percent of the time prevent tainted data from reaching the db table, the other 1 percent well there are clever hackers out there that can easily beat the system.

Using prepare statements has nothing to do with whether fields are tainted or not.

Tainted means that the field has at some point contained unsanitized data so you can’t tell from the field name that it is not junk data.

Prepare statements do not prevent someone inserting millions of rows of junk data into the database if tainted fields are referenced in the bind statement.

I mean not prepared statements, but things that contains harmful content, like an XSS attack

That has nothing to do with sanitizing. You sanitize data when it is first input so as to ensure that you are not processing junk.

Sanitizing is an input function done before you do any other processing.

prepared statements and other code intended to prevent injection are output functions - done immediately before you output the data at the opposite end of the script from where you sanitize.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.