如何保护我的站点免受SQL注入攻击?我正在使用PHP和mysql。我必须改变我的mysql查询吗?
例如,我有一个这样的查询:
<?php
$q=$_GET["q"];// im getting the Q value from the other form,from drop down box[displaying data using Ajax
$a1=$_POST['hosteladmissionno'];
$a2=$_POST['student_name'];
$a3=$_POST['semester'];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hostel", $con);
$a1="SELECT hosteladmissionno,student_name,semester FROM registration
WHERE mess_type ".$q."' AND status_flag=1";
$result = mysql_query($a1);
if ($result === false) {
die(mysql_error());
}
echo "<table border='1' width=80%>
<tr>
<th width=5%> S.No</th>
<th width=10%>H.Admin No</th>
<th width=10%>Student Name</th>
<th width=5%>No of Days</th>
</tr>";
$i=0;
while($row = mysql_fetch_array($result))
{
$i=$i+1;
echo "<tr>";
echo "<td align=center>" .$i."</td>";
echo "<td size=10 align=center>" . $row['hosteladmissionno'] . "</td>";
echo "<td size=35 align=center>" . $row['student_name'] . "</td>";
echo "<td align=center> <input type='text' name='days' size=2> </td> ";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>我是否必须在查询中包含任何更改以避免注入攻击?任何建议都会提前helpful.Thanks。干杯!
发布于 2011-03-29 14:15:50
您的查询看起来(编辑:在查询的第一个版本中出现)是完全静态的-即它不使用任何用户提供的数据。在这种情况下,没有SQL注入的风险。
SQL注入攻击涉及获取用户输入并将其直接包含在SQL查询中,而不是使用参数化SQL语句并以这种方式包含用户提供的值的首选方法。(我不知道PHP中的细节是如何实现的…我当然希望这是可能的。)
编辑:好的,现在你已经修改了你的代码,包括:
$a1="SELECT hosteladmissionno,student_name,semester FROM registration
WHERE mess_type ".$q."' AND status_flag=1";其中,从文本框中检索$q。现在我假设你真的想说第二行:
WHERE mess_type='".$q."' AND status_flag=1";但这仍然容易受到SQL注入攻击。假设q的值为:
' OR 'x'='x然后,您的SQL语句将结束为
SELECT hosteladmissionno,student_name,semester FROM registration
WHERE mess_type='' OR 'x'='x' AND status_flag=1这显然不是你想要的逻辑。
您应该使用这些值的参数,如此PHP prepared statement page所示。
发布于 2011-03-29 14:16:11
当您从用户获取数据并在查询中使用它,而没有采取措施阻止它对该查询进行预期的更改时,就会发生SQL注入攻击。
由于在该查询中根本没有使用任何变量,所以不能这样做,所以它是安全的。
有关更多信息,请参阅http://bobby-tables.com/。
发布于 2011-03-29 14:17:25
我得到的建议是使用准备好的语句。在实践中,使用一个优秀的数据库抽象层很容易做到这一点:
https://stackoverflow.com/questions/5468603
复制相似问题