php - 文本输出中的斜杠

标签 php mysql mysql-real-escape-string html-entities

在表单中,我要求用户输入一些文本。我将使用 $_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/

相关文章:

PHP/MySQL - 好友列表 SQL 查询

PHP/MySQL : Check whether email exists in database?

PHP多维排序?

php - 从产品类别及其所有子类别中获取产品

php - 我怎样才能让我的数据库在这个 "foreach"循环中使用 PHP 更新不止一次?

php - mysql_real_escape_string 和撇号问题

php - mysql_real_escape_string 只转义一种类型的引号

javascript - jQuery - 复选框数据发布到 php

php - 使用 Zend 框架进行连接更新

php - 需要 $_SESSION 变量的 mysql_real_escape_string() 吗?