Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Try out my first PHP web app! Reply To: Try out my first PHP web app!

#182558
__
Participant

Probably not. Sanitizing all input in the same way is not a good approach. In order to sanitize input effectively, you need to know what you’re sanitizing it for. For output, you might need to use htmlspecialchars. For a database query, htmlspecialchars won’t help: you need to use mysqli->real_escape_string. For prepared statements, you should not do anything, because the DB will handle escaping your bound parameters on its own.

So, what’s wrong with using real_escape_string and prepared statements, you might ask…? It won’t hurt anything, right? Well, not in the sense that it creates some immediate security risk*, but you will end up with literal \s permanently stored in the database. (You can’t simply remove them, because there might have been real backslash characters in the original input—no way of knowing, now.) Probably not what you wanted.

* though other combinations of well-intended functions might.

When you try to solve three problems at once, you are almost guaranteed to create two new problems in the process. Don’t sanitize input until you know what you are doing with it. In most cases, this means it is best to do nothing until you actually use the data.

edit
The “wait” approach also has the benefit of putting your sanitization code very close to the use it needs to safeguard, which makes it easier to ensure that you’ve done it correctly.