Sql注入以及如何在php中验证它

时间:2018-03-03 11:19:52

标签: php sql-injection

以下代码是否容易受到Sql注入以及如何验证?

$query=("select * from table2 where username = '$username'and password='$password'");
$result=  mysqli_query($connect, $query);
       $row=  mysqli_fetch_assoc($result);
    if  ($username==$row['username']&&$password==$row['password'])
    {
        header('location:header.php');//to go header
        }
else
{
    header('location:insert_p.php');}

1 个答案:

答案 0 :(得分:1)

是的,您的代码似乎容易受到SQL注入攻击。看看这一行:

$query=("select * from table2 where username = '$username' and password='$password'");

在这里,您将变量$username$password直接传递给数据库。如果$username包含类似admin'; --的字符串,则不会检查密码。

如何验证?

请确保您直接放入SQL语句的每个变量都是安全的。

其他解决方案?

  • 您可以使用mysqli_real_escape_string()docs)来转义'等特殊字符。
  • 您可以使用预准备语句。他们分开代码和价值观。 This is a good start.