Search code examples
phpmysqlxsshtmlspecialchars

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.


Solution

  • An even better reason is that on truncating to fit a certain space you'll get stuck with abominations such as "&quo...". Resist the temptation to fiddle with your data more than the minimum required. If you're worried about reprocessing the data, cache it.