Is it better to convince / encode user input before storing it in the database or storing it as it is in the database and avoiding it when retrieving?

I am using the htmlspecialchars() function to prevent XSS attacks. I doubt that the best way to store data in a database is from the following.

Method 1: Save user-entered values ​​after applying the htmlspecialchars() function. Using this, user input "<script>" will become "& lt; script & gt;".

Method 2: Keep user input as is and use the htmlspecialchars() method when retrieving data and displaying it on the page.

The reason for my doubt is that I believe that using method 1 there will be overhead in the database, while using method 2 data needs to be converted again and again on demand via php. So I'm not sure which one is better.

For more information, I use htmlspecialchars($val, ENT_QUOTES, "UTF-8") to convert 'and' as well.

Please help me clear my doubts. Also explain if possible.

Thanks.

+4
source share
4 answers

An even better reason is that when truncated to fit a specific space, you are stuck with abominations such as "&quo..." . Resist the temptation to mess with your data for more than the minimum necessary. If you are worried about data processing, cache them.

+4
source
  • Why do you expect that you will always use data in an HTML context? "I <3 you" and "I & lt; 3 you" are not the same data. Therefore, save the data as provided in the database. There is no reason to save it.
  • HTML, avoiding data when and only when necessary, gives you confidence in what you know. It:

     echo htmlspecialchars($data); 

    much better than:

     echo $data; // The data should already come escaped from the database. // I hope. 
+9
source

My recommendation is to store data in a database in its purest form. The only reason you want to convert it to &lt;script&gt; , is that you will need to display it in the HTML document later. But the database itself does not need to know what you do with the data after it is received.

+3
source

Just like XSS attacks, aren't you worried about SQL injection attacks if you enter user input into a database? In this case, you will want to avoid user input before placing it in the database.

0
source

Source: https://habr.com/ru/post/1399138/


All Articles