When to use: htmlspecialchars?

I need to convert strings to special characters using:

htmlspecialchars 

My question is should I convert my data before sending it to the database or should I convert it before displaying?

+4
source share
4 answers

You must sanitize the data before inserting it into the database and avoid it when searching.

htmlspecialchars used for escaping, so it should be after you retrieve it from the database.

+6
source

As a general rule, it is best not to modify the source data before saving it. It will bind your data to the specific context in which you use it. What if you ever need another way to display it, for example. in pdf or in format? Then you will have the html objects in your text and will have to return them.

IMHO In this regard, performance considerations are secondary, but caching techniques can be used for this.

So, on the bottom line, I suggest you always prepare the lines before displaying.

+2
source

I assume that the data is already escaped sanitized before you put it in the database so that it is safe. From there I try to change the data on the way to the database as little as possible.

Keep in mind that you are probably using a copy now on your website, but later on the line you can use it on another device or when printing. If you use htmlspecialchars before going to the database, you will have to clear it if you want to use it for something other than HTML. Formatting dates as strings before putting them into the database is common, but if you want to change the format ...

+2
source

This makes the data safe to be inserted into an HTML document. Use it before embedding it in an HTML document, not in a database.

+1
source

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


All Articles