What is the correct way to detect whether string inputs contain HTML or not?

前端 未结 13 658
旧时难觅i
旧时难觅i 2020-12-23 15:08

When receiving user input on forms I want to detect whether fields like \"username\" or \"address\" does not contain markup that has a special meaning in XML (RSS feeds) or

13条回答
  •  囚心锁ツ
    2020-12-23 15:19

    I think you answered your own question. The function htmlspecialchars() does exactly what you need, but you should not use it until you write the user input to a page. To store it in a database there are other functions, like mysqli_real_escape_string().

    As a rule of thumb, one can say that you should escape user input only when needed, for the given target system:

    1. Escaping user input often means a loss of the original data, and different target systems (HTML output / SQL / execution) need different escaping. They can even conflict with each other.
    2. You have to escape the data for the given purpose anyway, always. You should not trust even the entries from your database. So escaping when reading from user input does not have any big advantage, but double escaping can lead to invalid data.

    In contrast to escaping, validating the content is a good thing to do early. If you expect an integer, only accept integers, otherwise refuse the user input.

提交回复
热议问题