【问题标题】:allow html but protect from mysqli injection [duplicate]允许html但防止mysqli注入[重复]
【发布时间】:2014-01-08 19:37:38
【问题描述】:

过去几天我一直在尝试这样做,我尝试了很多功能,例如

strip_tags , mysqli_real_escape_string , ..etc

// Prevent MySQL Injection Attacks
function cleanQuery($connector,$string){
    if(get_magic_quotes_gpc())  // prevents duplicate backslashes
        $string = stripslashes($string);
    return mysqli_escape_string($connector,$string);
}

但没有人给我想要的结果。

我想要的是输入文章文本,允许 html 编辑但防止 mysqli 注入...有人可以帮忙吗?

例如: 我有这个:

$data     = $_POST['data'];


echo "<form method='POST' action='index.php?do=check'>
<textarea rows='10' name='data' cols='50'>$data</textarea>
<input type='submit' value='send' name='B1'>
</form>
  ";



mysqli_query($conn,"insert into table(field)values('$data')"); 

数据的价值是:

<p align="center"><b><font size="6">test</font></b></p>
<table border='1' width='100%'>
    <tr>
        <td>&nbsp;what's your name ?</td>
        <td>&nbsp;my name is `Jhone`</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

html 输入

那么我怎样才能毫无问题地将它插入数据库呢?

【问题讨论】:

  • myslqi 准备好的报表将为您提供所有必要的保护
  • 使用准备好的语句
  • 是什么让您认为代码无法保护您免受 SQL 注入? (这是次优的(准备好的语句是一种更好的方法),奇怪的是在输出准备的同时进行输入修复,但我没有看到任何会使其失败的东西。
  • DEFINE(预期)结果。

标签: php html mysqli code-injection


【解决方案1】:

正如你们所说,通过 prepare 解决了问题, 花时间随心所欲地工作,但它奏效了..谢谢大家

用于选择和执行:

$stmt = $connector->prepare('select * from TABLENAME where FIELD1 = ? and FIELD2 = ?');
$stmt->bind_param('ss', $FIELD1_VALUE,$FIELD2_VALUE);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

$stmt->close();

IN 第 1 行:使用 ? 更改要插入值的位置 IN lne 2 :对于每个 ? ,放入 s 并添加值,如上所示。

用于插入:

$stmt = $connector->prepare('insert into TABLE(FIELD1,FIELD2,FIELD3)values(?,?,?)');
$stmt->bind_param('sss',  $FIELD1_VALUE,$FIELD2_VALUE,$FIELD3_VALUE);

if ($stmt->execute()){
echo "data added ";

}else{

echo "Error adding data ".$stmt->error ;
}

$stmt->close();

同样的规则适用

希望对您有所帮助! 问候,

【讨论】:

  • 能否请您在答案中分享您改进后的代码,以便其他人学习?
  • @MarcelKorpel,回答。已更新。
【解决方案2】:

MySQLi...试试这个代码:

// Prevent MySQL Injection Attacks
function cleanQuery($connector,$string){
    return $connector->real_escape_string($string);
}

如果您使用 mysqli,此代码将非常适合您。

【讨论】:

  • 什么是addslashesh?你的意思是addslashes ;-)
  • 天哪,为什么!为什么在 real_escape_String 之后添加斜杠()??
  • 不,不,不,不要使用addslashes!除此之外,代码与OP相同。
  • @DamienPirsy 小细节:之前 real_escape_string.
  • @MarcelKorpel 你说得对,我写的很匆忙 :),但这也是我的意思
猜你喜欢
  • 2012-08-04
  • 2016-04-06
  • 2020-08-09
  • 2012-03-29
  • 2018-04-26
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多