PHP Prepared语句登录

时间:2015-02-28 18:45:47

标签: php mysql login passwords sql-injection

我正在将密码哈希和SQL注入防御添加到我的登录系统中。目前,我遇到了错误。

    <?php
session_start(); //start the session for user profile page

define('DB_HOST','localhost'); 
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password

$con = new PDO('mysql:host=localhost;dbname=test','root','');

function SignIn($con){
    $user = $_POST['user']; //user input field from html
    $pass = $_POST['pass']; //pass input field from html
    if(isset($_POST['user'])){ //checking the 'user' name which is from Sign-in.html, is it empty or have some text
        $query = $con->prepare("SELECT * FROM UserName where userName = :user") or die(mysqli_connect_error());
        $query->bindParam(':user',$user);
        $query->execute();

        $username = $query->fetchColumn(1);
        $pw = $query->fetchColumn(2);//hashed password in database
        //check username and password
        if($user==$username && password_verify($pass, $pw)) {
            // $user and $pass are from POST
            // $username and $pw are from the rows

            //$_SESSION['userName'] = $row['pass'];
            echo "Successfully logged in.";
        }

        else { 
            echo "Invalid."; 
        }
    }
    else{
        echo "INVALID LOGIN";
    }
}

if(isset($_POST['submit'])){
    SignIn($con);
}
?>

在上面的代码中,当我输入有效的用户名和密码时,系统会输出&#34; Invalid&#34;。它可能是if语句中password_verify()的错误(因为如果我删除它,我会成功登录)。我很确定我已经正确地完成了查询的准备,绑定和执行了吗?有谁知道它为什么会这样做?

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在执行SELECT *,并使用fetchColumn,因此结果取决于返回的列顺序。您应该选择所需的特定列,或者将整行作为关联数组获取,并按列名访问它。

您还应该解决其他两个问题:

  • 当你正在使用PDO时,你不应该使用mysqli_connect_error()。正确的功能是$con->errorInfo()
  • 您使用连接设置定义了一些常量,但是您不能在PDO()调用中使用它们,而是重复这些值。

答案 1 :(得分:1)

使用

// it will be an array('name' => 'John', 'password_hash' => 'abcd')
// or FALSE if user not found
$storedUser = $query->fetch(PDO::FETCH_ASSOC);

而不是

$username = $query->fetchColumn(1);
$pw = $query->fetchColumn(2);

因为fetchColumn移动结果的光标。因此,第一次调用提取第一行的第一列,第二次调用将从第二行提取数据!

相关问题