which of these two ways best prevents the xss attack.
- HTMLEntities when saving to db
- HTMLEntities on display / echo
2 - you must convert to the target format at the last moment. This will save you from problems in the future if, for example, you decide that you want to use the same content in an email, in PDF format, as text for the user to edit, etc. Etc.
I find the first one better, because you may forget to add this when displaying
You can forget when pasting into a database.
In addition, not all data enters the database. for example, Previewing data to be inserted or data returned to the form due to errors are both possible XSS vectors. You do not want to deal with such things as "Encoding before entering into the database or re-reflection in the document if it was not from the database." Exceptions are the best way to get into a situation when you forget to code.
source share