这段代码有什么问题无法解决问题

时间:2015-07-24 23:47:02

标签: php mysqli

我是开发新手,过去3天我一直花在我写的一段代码上。这是它需要做的:它需要检查电子邮件和密码是否填写在登录表单中。它还必须检查数据库是否设置为“活动”。 $ row返回一个布尔值。那么,如果将数据库中的状态设置为活动状态,我怎么可能被重定向到错误页面? 有人可以解释并通过代码和我做错了吗?我一直在网上搜索,但找不到合适的答案。这是我的代码:

    <?php

        include_once 'db_connect.php';
        include_once 'functions.php';

        sec_session_start(); // Our custom secure way of starting a PHP session.
        error_reporting(E_ALL);
        ini_set('display_erros', 1);
        if (isset($_POST['email'], $_POST['p'])) {
            $email = $_POST['email'];
            $password = $_POST['p']; // The hashed password.
            $query = "SELECT * FROM `members` WHERE `email` = '$email'AND status = 1 LIMIT 1";
            $result = mysqli_query($mysqli, "SELECT COUNT(`ID`) AS count FROM members WHERE email='$email' AND `status`='1'");
            $row = mysqli_fetch_assoc($result);
            var_dump($row['count'] < 1);

        if (login($email, $password, $mysqli) === true && $row === true) {
               // Login success 
                header('Location: ../index2.php');
            } else {
                // Login failed 


                  header('Location: ../index.php?error=1');
            }
        } else {
            // The correct POST variables were not sent to this page. 
            echo 'Invalid Request';
        }

    function login($email, $password, $mysqli) {
        // Using prepared statements means that SQL injection is not possible. 
        if ($stmt = $mysqli->prepare("SELECT id, username, password, salt 
            FROM members
           WHERE email = ?
            LIMIT 1")) {
            $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
            $stmt->execute();    // Execute the prepared query.
            $stmt->store_result();

            // get variables from result.
            $stmt->bind_result($user_id, $username, $db_password, $salt);
            $stmt->fetch();

            // hash the password with the unique salt.
            $password = hash('sha512', $password . $salt);
            if ($stmt->num_rows == 1) {
                // If the user exists we check if the account is locked
                // from too many login attempts 

                if (checkbrute($user_id, $mysqli) == true) {
                    // Account is locked 
                    // Send an email to user saying their account is locked
                    return false;
                } else {
                    // Check if the password in the database matches
                    // the password the user submitted.
                    if ($db_password == $password) {
                        // Password is correct!
                        // Get the user-agent string of the user.
                        $user_browser = $_SERVER['HTTP_USER_AGENT'];
                        // XSS protection as we might print this value
                        $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                        $_SESSION['user_id'] = $user_id;
                        // XSS protection as we might print this value
                        $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                    "", 
                                                                    $username);
                        $_SESSION['username'] = $username;
                        $_SESSION['login_string'] = hash('sha512', 
                                  $password . $user_browser);
                        // Login successful.
                        return true;
                    } else {
                        // Password is not correct
                        // We record this attempt in the database
                        $now = time();
                        $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                        VALUES ('$user_id', '$now')");
                        return false;
                    }
                }
            } else {
                // No user exists.
                return false;
            }
        }
    }
    function checkbrute($user_id, $mysqli) {
        // Get timestamp of current time 
        $now = time();

        // All login attempts are counted from the past 2 hours. 
        $valid_attempts = $now - (2 * 60 * 60);

        if ($stmt = $mysqli->prepare("SELECT time 
                                 FROM login_attempts 
                                 WHERE user_id = ? 
                                AND time > '$valid_attempts'")) {
            $stmt->bind_param('i', $user_id);

            // Execute the prepared query. 
            $stmt->execute();
            $stmt->store_result();

            // If there have been more than 5 failed logins 
            if ($stmt->num_rows > 5) {
                return true;
            } else {
                return false;
            }
        }
    }

    function login_check($mysqli) {
        // Check if all session variables are set 
        if (isset($_SESSION['user_id'], 
                            $_SESSION['username'], 
                            $_SESSION['login_string'])) {

            $user_id = $_SESSION['user_id'];
            $login_string = $_SESSION['login_string'];
            $username = $_SESSION['username'];

            // Get the user-agent string of the user.
            $user_browser = $_SERVER['HTTP_USER_AGENT'];

            if ($stmt = $mysqli->prepare("SELECT password 
                                          FROM members 
                                          WHERE id = ? LIMIT 1")) {
                // Bind "$user_id" to parameter. 
                $stmt->bind_param('i', $user_id);
                $stmt->execute();   // Execute the prepared query.
                $stmt->store_result();

                if ($stmt->num_rows == 1) {
                    // If the user exists get variables from result.
                    $stmt->bind_result($password);
                    $stmt->fetch();
                    $login_check = hash('sha512', $password . $user_browser);

                    if ($login_check == $login_string) {
                        // Logged In!!!! 
                        return true;
                    } else {
                        // Not logged in 
                        return false;
                    }
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    }

    function esc_url($url) {

        if ('' == $url) {


      return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&amp;', '&#038;', $url);
    $url = str_replace("'", '&#039;', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

1 个答案:

答案 0 :(得分:0)

现在似乎有用了。我修改了一些代码。现在我尝试使用mysqli_real_escape_string来阻止SQL注入。我正在阅读SQL注入,但我还有很多东西需要学习。我所做的是更改数据库设置而不是$ row [&#39; status&#39;] === true。我将其更改为$ row [&#39; status&#39;] === NULL。我以这种方式改变它因为vardump在激活返回时的状态为NULL。

 if (isset($_POST['email'], $_POST['p'])) {
        $email = $_POST['email'];
        $password = $_POST['p']; // The hashed password.
        $query = "SELECT * FROM `members` WHERE `email` = '". mysqli_real_escape_string($mysqli,$email) ."'AND status = 1 LIMIT 1"; 
       // check the changes around $email and mysqli_real_escape_string use to prevent SQL Injection
        $result = mysqli_query($mysqli,$query) or die(mysqli_error($mysqli)); // execute previous written query
    $row = mysqli_fetch_assoc($result); // fetch record
    //var_dump($row['status'] < 1);



    if ($row['status'] === NULL && login($email, $password, $mysqli) === true) {
               // Login success 
        header('Location: ../index2.php');
    } else {
        // Login failed 

        header('Location: ../index.php?error=1');
    }
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}