为什么我的代码不容易受到SQL注入攻击?

时间:2018-05-29 19:40:08

标签: php sql-injection

尝试制作易受SQL注入攻击的简单PHP应用。 如果用户/通行证是正确的,它让我登录,如果没有,它就不会。 但是,当我尝试其中任何一个时:

' OR '1' = '1

' OR '1'='1

' OR '1' = '1' --

出现以下错误消息:

  

警告:mysqli_fetch_array()要求参数1为mysqli_result,第14行给出布尔值

     

警告:mysqli_num_rows()要求参数1为mysqli_result,第15行给出布尔值

我试图在两个字段中注入并使用有效的用户名/注入和注入/有效密码组合,但无济于事。 有人可以指出问题吗?谢谢。代码:

<!-- index.php -->

<?php
include("config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
    if(isset($_POST["sbm"])){
        $username = $_POST['username'];
        $password = $_POST['password']; 
    }

    $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
    $result = mysqli_query($conn,$sql);
    $row = mysqli_fetch_array($result);
    $count = mysqli_num_rows($result);

    if($count == 1) {
        $_SESSION['login_user'] = $username;
        header("location: welcome.php");
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form method = "post">
        <label>Username</label><input type = "text" name = "username"/><br /><br />
        <label>Password</label><input type = "password" name = "password"/><br/><br />
        <input type = "submit" value = "Login" name="sbm"/><br />
    </form>
</body>
</html>

<!-- config.php -->

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'db');
$conn = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

<!-- welcome.php -->

<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome</h1> 
</body>
</html>

1 个答案:

答案 0 :(得分:1)

一种经典的SQL注入方式:

Query: SELECT * FROM Users WHERE username='$username' AND password='$password'

为用户名和密码值插入以下内容:

$ username = 1&#39;或者&#39; 1&#39; =&#39; 1 和 $ password = 1&#39;或者&#39; 1&#39; =&#39; 1。

查询然后显示:

SELECT * FROM Users WHERE username='1' OR '1' = '1' AND password='1' OR '1' = '1' 

查询返回一个或多个值,因为条件始终为真(OR 1 = 1)。