4

我需要使用以下方法将字符串转换为特殊字符:

 htmlspecialchars

我的问题是,我应该在将数据提交到数据库之前进行转换,还是在显示之前进行转换?

4

4 回答 4

6

您应该在将数据插入数据库之前对其进行清理,并在检索时对其进行转义。

htmlspecialchars用于转义,所以它应该是在你从数据库中获取它之后。

于 2013-06-06T14:53:50.043 回答
2

通常最好不要在存储源数据之前对其进行修改。它将您的数据与您使用它的特定上下文联系起来。如果您需要一种不同的显示方式,例如以 PDF 或文本格式显示它怎么办?然后,您将在文本中包含 html 实体,并且需要将它们转换回来。

恕我直言,性能考虑在这方面是次要的,仍然可以使用缓存技术来实现这一点。

因此,最重要的是,我建议您始终在展示之前准备好您的琴弦。

于 2013-06-06T14:56:08.357 回答
2

我假设在您将数据放入数据库之前已经对其进行了转义处理,因此它是安全的。从那里开始,我尝试在通往数据库的途中尽可能少地更改数据。

The thing to remember is that maybe you're using the copy now on your website, but later down the line you may like to use it on a different device or on print. If you use htmlspecialchars before it goes to the database, you'll have to clean it up if you want to use it for something other than HTML. Formatting dates as strings before putting them into a database is a common one, but when you want to change the format...

于 2013-06-06T14:56:12.467 回答
1

它使数据可以安全地插入 HTML 文档。在将其插入 HTML 文档而不是数据库之前使用它。

于 2013-06-06T14:53:39.267 回答