SQL注入攻击

Coo*_*eze 5 php mysql sql sql-injection

如何保护我的网站免受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);
?>
Run Code Online (Sandbox Code Playgroud)

我是否必须在查询中包含任何更改以避免注入攻击?任何建议都会有所帮助.谢谢.干杯!

Jon*_*eet 3

您的查询似乎(编辑:出现在查询的第一个版本中)完全静态 - 即它不使用任何用户提供的数据。在这种情况下,就不存在 SQL 注入的风险。

SQL 注入攻击涉及获取用户输入并将其直接包含在 SQL 查询中,而不是使用参数化 SQL 语句并以这种方式包含用户提供的值的首选方法。(我不知道 PHP 是如何完成的细节......我当然希望这是可能的。)

编辑:好的,现在您已经更改了代码,包括:

$a1="SELECT  hosteladmissionno,student_name,semester FROM registration 
WHERE mess_type ".$q."' AND  status_flag=1";
Run Code Online (Sandbox Code Playgroud)

$q从文本框中检索的位置。现在我假设你真正的意思是第二行是:

WHERE mess_type='".$q."' AND  status_flag=1";
Run Code Online (Sandbox Code Playgroud)

但这仍然容易受到 SQL 注入攻击。假设 q 的值为:

' OR 'x'='x
Run Code Online (Sandbox Code Playgroud)

你的 SQL 语句最终将是

SELECT hosteladmissionno,student_name,semester FROM registration 
WHERE mess_type='' OR 'x'='x' AND  status_flag=1
Run Code Online (Sandbox Code Playgroud)

这显然不是你所追求的逻辑。

您应该对值使用参数,如PHP 准备好的语句页面所示。