首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP和MySQL中如何避免SQL注入,同时在文本区换行?

在PHP和MySQL中如何避免SQL注入,同时在文本区换行?
EN

Stack Overflow用户
提问于 2018-09-03 23:45:47
回答 1查看 1K关注 0票数 4

我想要的是当用户在描述框即:textarea中的HTML然后所有的数据被安全地存储在SQL数据库中,但如果用户给链接,那么链接也变成文本,但当用户在描述文本框中回车或换行符时,它保存在数据库中,当从数据库检索它时,换行符将再次显示。

代码语言:javascript
复制
<textarea name"description" id="description" rows="4" cols="50">
//In The text area the user enter the text. Here I want if user gives html links then links becomes text and if user give line break then line break store in the database and I can get back as it is how user submitted the form. Also I want to store data securely for avoiding sql injection but dont have the exact idea how to do it.
</textarea>

$text = $_POST['description'];
$text = htmlentities($text); // Here I want to remove html entities for avoiding sql injection
$text = mynl2br($text);
// Now Fire Insert Query All the data save but while retrieving the data I am not able to get line break and turning links to the text.


function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

这就是我正在做的,但链接仍然是链接,当我检索文本时,显示的文本没有换行。一行或一段中的所有文本。

请建议我在上面的代码中做错了什么。怎样才能避免sql注入,并能够安全地存储和检索数据。

EN

回答 1

Stack Overflow用户

发布于 2018-09-04 00:05:02

为了保留新行,你必须保留原来的换行符,如果你替换它们,你必须将它们替换回来,或者你只能在页面上显示文本时使用nl2br (推荐),而不是在存储或检索文本进行编辑之前。

同样的道理也适用于链接,在存储之前不要更改它们,只有当您在页面上显示它时才替换它,这样您就不会再次编辑它,并且您可以随时修改链接生成,因为您不存储结果,而是原始结果。

为了避免SQL注入,您不希望使用这些神奇的函数(htmlentities、strip_tags、magic_quotes等-有很多函数,但没有一个是完美的)--最好的解决方案是使用预准备语句:https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.quickstart.prepared-statements.html

它通过为值提供占位符来解决问题,这样用户输入就不能修改查询。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52152874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档