Okay I was wondering when should I sanitize my code, when I add store it in the database or when I have it displayed on my web page or both?
I ask this question beca
Rule is thumb is to sanitize ALL user input. Never trust the user.
There are distinct threats you are (probably) talking about here:
What's harmful to your database is not necessarily harmful to the users (and vice versa). You have to take care of both threats accordingly.
In your example:
You probably want to use the purifier prior to data insertion - just ensure it's "purified" by the time the user gets it.
You might need to use striplashes() on data retrieved from the db to display it correctly to the user if magic_quotes
are on
I think you would want to escape
the input (to avoid SQL injections) and sanitize
(to avoid scripting attacks) at the same time, as you're inserting into the database.
This way, you only need to run the sanitizer
once on insertion, rather than (potentially) millions of times on display.
You should always encode data when you display it. This way your application can do no wrong. This will protect you from bad data no matter how it came to be.
When you are putting something in the database, you make sure it's safe to put in the database.
When you are about to display something in a browser, you make sure it's safe to display it in the browser.
If you make something browser-safe before you put it in the database, then you are now picking up the habit of trusting that things will be browser-safe when they come out of the database. It's not a good habit to trust user data, even if you're pretty sure you cleaned it previously. Also makes it easy to forget to sanitize before output if you're using someone else's database or code.