将文本区域保存到 MySQL 并保留换行符
想象一个博客或 cms 系统(PHP 和 MySQL)。我想让用户在文本区域中输入一些文本并将其保存到数据库中。数据库中该字段的类型是TEXT。
我想保留换行符并稍后打印它们。我知道我可以使用 PHP 的 nl2br 函数来做到这一点,但是如何保护该字符串免受 SQL 注入攻击(假设我不能使用准备好的语句)。如果我在上面使用 mysql_real_escape_string ,它就不会再显示换行符。
$text = 'one line
another line';
$text = mysql_real_escape_string($text);
/* save to db, fetch it some time later */
echo nl2br($text); /* output: one line\r\nanotherline */
Imagine a blog or cms system (PHP and MySQL). I want to let the user enter some text in a textarea and save it to the database. The type of the field in the database is TEXT.
I want to preserve line breaks and print them later. I know I can do this with PHP's nl2br
-function, but how do I protect this string against SQL-injection attacks (let's assume I can't use prepared statements). If I use mysql_real_escape_string
on it, it does not show me line breaks anymore.
$text = 'one line
another line';
$text = mysql_real_escape_string($text);
/* save to db, fetch it some time later */
echo nl2br($text); /* output: one line\r\nanotherline */
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
mysql_real_escape_string
不会删除换行符,而是转义换行符。在存储字符串时转义字符串应该可以正常工作,并在数据为 <强>输出。这是最好的方法。
mysql_real_escape_string
doesn't remove line breaks, it escapes them.It should work okay to escape the string when storing it, and applying
nl2br
(possibly in combination withhtmlspecialchars()
to prevent users from entering raw HTML) when the data is output. That's the best way to go.mysqli_real_escape_string
会将您的回车符替换为\r\n
,因此您需要使用str_replace()
将其取回。但是,它在您的浏览器/电子邮件客户端中仍然不可见。这就是nl2br()
发挥作用的地方:代码已经过测试,您可以使用它。
mysqli_real_escape_string
will replace your carriage return with\r\n
, hence you will need to get it back usingstr_replace()
. However, it still won't be visible in your browser / email client. That's wherenl2br()
comes into play:The code is tested, you can use it.
您没有看到
"\n"
文字代替换行符吗?如果是这样,您的代码会做一些令人讨厌的事情,很可能您会两次转义数据。
或者,从数据库获取数据后不执行 mysql_real_escape_string() 吗?
不管怎样,您必须进行一些调试 - 一项调查,看看您的数据在每个阶段发生了什么。只需打印$_POST['textarea_name']、SQL查询等
查看您失去休息的时刻并找出违规者
注意:
mysql_real_escape_string 不保护任何内容免受任何攻击。它逃脱了分隔符。
nl2br 不保留任何东西。它将 HTML 标记添加到换行符中。
don't you see
"\n"
literals in place of line breaks?if so, your code doing some nasty things, most likely you escape your data twice.
or, don't you do mysql_real_escape_string() after getting data from database?
Anyway, you've got to do some debugging - an investigation, to see what happens to your data on every stage. Just print out $_POST['textarea_name'], SQL query, etc.
To see the moment you lose your breaks and to find out an offender
Notes:
mysql_real_escape_string do not protect anything from any attack. It escapes delimiters.
nl2br do not preserve anything. It adds an HTML tag to line breaks.