Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it better to escape/encode the user input before storing it to database or to store it as it is in database and escape it while retrieving?

I am using htmlspecialchars() function to prevent XSS attacks. I have doubt regarding what is the better method to store the data in database from following.

Method 1 : Store the user input values after applying htmlspecialchars() function. Using this it user input "<script>" will become "&lt;script&gt;" .

Method 2 : Store the user input as it is and apply htmlspecialchars() method while retrieving the data and displaying it on the page.

The reason for my doubt is that I believe using method 1 there will be overhead on database, while using method 2 data need to be converted again and again when requested through php. So I am not sure which one is better.

For more information, I am using htmlspecialchars($val, ENT_QUOTES, "UTF-8") so that will convert ' and " as well.

Please help me clear my doubt. Also provide explanation if possible.

Thanks.

like image 633
Vivek Vaghela Avatar asked Mar 01 '12 08:03

Vivek Vaghela


People also ask

What does it mean to escape user input?

User input is a string. Escaping is done when you want to insert some characters into some HTML / SQL / Whatever code which insists on interpreting some characters into special functionalities.

How do I escape data before storing it in the database in PHP?

addslashes function enables us to escape data before storage into the database. $str = "O'Reilly?"; eval("echo '" . addslashes($str) .


1 Answers

  1. Why do you expect that you will always use the data in an HTML context? "I <3 you" and "I &lt;3 you" is not the same data. Therefore, store the data as it's intended in the database. There's no reason to store it escaped.
  2. HTML escaping the data when and only when necessary gives you the confidence to know what you're doing. This:

    echo htmlspecialchars($data);
    

    is a lot better than:

    echo $data; // The data should already come escaped from the database.
                // I hope.
    
like image 175
deceze Avatar answered Oct 21 '22 05:10

deceze