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?

一笑奈何 提交于 2019-12-01 18:30:45

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.

  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.
    

My recommendation is to store the data in the database in its purest form. The only reason you want to convert it into &lt;script&gt; is because you'll need to display it in a HTML document later. But the database itself doesn't have a need to know about what you do with the data after you retrieve it.

As well as XSS attacks, shouldn't you also be worried about SQL injection attacks if you're putting user input into a database? In which case, you will want to escape the user input BEFORE putting it into the database anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!