防止SQL注入

时间:2014-08-26 10:35:00

标签: php sql security sql-injection

有人告诉我,我的代码可能会被一位告诉我不够安全的朋友注入SQL。但是,他们并没有告诉我如何防范这种情况。有人可以帮忙吗?

代码:

<?php
session_start();

ob_start();

if(empty($_POST) === false) {
    if(isset($_POST['username'])) {

        $db = new mysqli('localhost', 'test', '', 'fma');

        if(userExists($username)){

            if(verifyPassword($username, $password)) {
                $errors[] = '<span class="login-correct">Successfully logged in</span>';
                $_SESSION['loggedIn'] = true;
                $_SESSION['username'] = $username;
                header ("Location: index.php");
            }
            else {
                $errors[] = '<span class="login-wrong">Password is incorrect</span>';
                $_SESSION['loggedIn'] = false;
                $_SESSION['username'] = '';
            }
        } 
        else {
            $errors[] = '<span class="login-wrong">No user exists with that username</span>';
            $_SESSION['loggedIn'] = false;
            $_SESSION['username'] = '';
        }
    }
}

function verifyPassword($username, $password) {

    $db = new mysqli('localhost', 'test', '', 'fma');

    $result = $db->query('
    SELECT password
    FROM users
    WHERE username = "'.$username.'"
    LIMIT 1
    ');

    while($row = $result->fetch_object()) {     

        if(crypt($password, $row->password) == $row->password) {
            return true;
        }
        else {
            return false;
        }
    }
}

function userExists($username) {

    $db = new mysqli('localhost', 'test', '', 'fma');

    $result = $db->query('
    SELECT username
    FROM users
    WHERE username = "'.$username.'"
    LIMIT 1
    ');

    if(!$result) {
        echo $db->error;
    }

    return (bool)$result->num_rows;
}

ob_flush();
?>

提前感谢,Gab。

0 个答案:

没有答案