如何在使用 htmlspecialchars() 和 htmlentities() 后检索原始文本

How to retrieve original text after using htmlspecialchars() and htmlentities()

我有一些文本要保存到我的数据库中。文本可能看起来像这样:Welcome & This is a test paragraph。当我在 PHP 中使用 htmlspecialchars()htmlentities() 处理后将此文本保存到我的数据库时,句子将如下所示:Welcome & This is a test paragraph.

当我检索并显示相同的文本时,我希望它是原始格式。我该怎么做?

这是我使用的代码;

$text= htmlspecialchars(htmlentities($_POST['text'])); 
$text= mysqli_real_escape_string($conn,$text);

有两个问题。

首先,您使用 htmlentitieshtmlspecialchars 双重编码 HTML 个字符。这两个函数都做同样的事情,但是 htmlspecialchars 只对具有 HTML 字符实体等价物(special 的字符子集进行处理。)所以在你的例子中,&符号将被编码两次(因为它 一个特殊字符),所以你实际得到的是:

$example = 'Welcome & This is a test paragraph';

$example = htmlentities($example);
var_dump($example);    // 'Welcome & This is a test paragraph'

$example = htmlspecialchars($example);
var_dump($example);    // 'Welcome & This is a test paragraph'

确定您需要使用其中的哪一个功能(可能 htmlspecialchars 就足够了)并只使用其中一个。

其次,您在错误的时间使用了这些功能。 htmlentitieshtmlspecialchars 不会对 "sanitize" 您的数据做任何操作以输入您的数据库。 (并不是说那是你的意图,因为你没有提到这一点,但很多人似乎确实试图这样做。)如果你想保护自己免受 SQL 注入,bind your values to prepared statements. 逃逸正如您目前使用 mysqli_real_escape_string 所做的那样很好,但还不够。

htmlspecialcharshtmlentities 有特定的用途:将要输出的字符串中的字符转换为 HTML 文档。等到你准备好了再使用它们。