When do I need to sanitize my PHP and MySQL code before storing it in a database or when is it displayed?

Well, I was wondering when should I sanitize my code, when I add it to the database, or when it appears on my web page or both?

I ask this question because I sanitize my code before it is stored in the database, but I never sanitize it when it is displayed to the user.

Here is an example of how I sanitize my code before storing it in a database.

$title = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($_POST['title']))); $content = mysqli_real_escape_string($mysqli, $purifier->purify($_POST['content'])); 
+4
source share
5 answers

There are various threats that you (possibly) are talking about here:

  • You need to clear the data that is inserted into the database in order to avoid SQL injection .
  • You also need to be careful with the data that is displayed to the user, as it may contain malicious scripts (if they were sent by other users). See Wikipedia Entry for Cross-Site Scripting (also known as XSS)

What is harmful to your database is not necessarily harmful to users (and vice versa). You must take care of both threats accordingly.

In your example:

You probably want to use a cleaner before entering data - just make sure it is โ€œcleanedโ€ by the time it is received.

You may need to use striplashes () for data retrieved from db in order to display them correctly to the user if magic_quotes enabled

+3
source

The rule is the thumb to sanitize all user input. Never trust the user.

+2
source

When you put something in the database, you will make sure that it is safe to place in the database.

When you are going to display something in the browser, make sure that it is safe to display it in the browser.

If you make something safe for the browser before you put it in the database, now you are in the habit of trusting that everything will be safe for the browser when they exit the database. It's not a good habit to trust user data, even if you are sure that you cleared it before. It also makes it easy to forget to sanitize before exiting if you are using someone elseโ€™s database or code.

+1
source

I think that you will want to escape to enter (to avoid SQL injection) and sanitize (to avoid script attacks) at the same time as inserting into the database.
Thus, you only need to run the sanitizer once upon insertion, and not (potentially) millions of times on the display.

0
source

You should always encode data when displaying it. Thus, your application cannot be wrong. This will protect you from bad data no matter how it turned out.

0
source

All Articles