如何在使用htmlspecialchars()和htmlentities()后检索原始文本
我有一些文本将保存到我的数据库中。文字可能如下所示:Welcome & This is a test paragraph
。当我在PHP中使用htmlspecialchars()
和htmlentities()
对其进行处理后,将此文本保存到我的数据库中时,该句子将如下所示:Welcome & This is a test paragraph
。如何在使用htmlspecialchars()和htmlentities()后检索原始文本
当我检索并显示相同的文本时,我希望它是原始格式。我怎样才能做到这一点?
这是我使用的代码;
$text= htmlspecialchars(htmlentities($_POST['text']));
$text= mysqli_real_escape_string($conn,$text);
有两个问题。
首先,您使用htmlentities
和htmlspecialchars
两种编码HTML字符。这两个函数都做同样的事情,但是htmlspecialchars
只对具有HTML字符实体等价物的字符子集(特殊那些)起作用。因此,以您的示例为例,该和号将被编码两次(因为它是特殊字符),所以你会真正得到是:
$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
就足够了),并且只使用其中的一个。
其次,您在错误的时间使用这些功能。 htmlentities
和htmlspecialchars
将不会做任何事情“清理”您的数据输入到您的数据库。 (并不是说这就是你的意图,因为你没有提到这一点,但很多人似乎都试图做到这一点。)如果你想保护自己免受SQL注入,bind your values to prepared statements.逃脱它,因为你正在与mysqli_real_escape_string
是好的,但它不是真的足够。
htmlspecialchars
和htmlentities
具有特定的用途:将要输出的字符串中的字符转换为HTML文档。只要等待,直到你准备好做到这一点。
'html_entity_decode'与'htmlentities'是对应的,顺便说一句:更好地改变你的sql使用准备好的语句并绑定'$ _POST ['text']'因为它是查询。我对你原始数据进行了修改。 – JustOnUnderMillions
为什么要这样做?插入数据不变,并修改它的目的,显示等。 – AbraCadaver