在表单中,我要求用户输入一些文本。我将使用 $_POST['text']
检索此文本。
用户输入字符串“It's my text!”
$newText = mysql_real_escape_string($_POST['text']);
现在在我将 $newText
插入到我要显示的数据库中后的同一页面上
将文本发送给用户,并使用 PHP 将其用作输入文本框的值。
// I want to make sure the user hasn't added any unsafe html in their string
$newText = htmlentities($newText);
echo "You've entered: " . $newText . "<br />";
echo "<form action=someaction.php method=post>";
echo "<input type=text value=\"" . $newText . "\">";
echo "</form>";
输出是:
You've entered: It\'s my text!
[It\'s my text!]
我如何避免这些斜线,我是否应该对我的数据做任何其他事情?
最佳答案
您正在通过 mysql_real_escape_string()
传递文本,顾名思义,它会转义字符串,包括撇号。 mysql_real_escape_string()
意味着仅 用于准备要保存到数据库的数据。向用户显示数据时不应使用它。
因此,解决方案很简单:删除该行并仅使用 htmlentities()
。在将字符串保存到数据库时(并且仅在那时)使用 mysql_real_escape_string()
。
关于php - 文本输出中的斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364716/