PHP Prepared语句登录


PHP Prepared statement login

我正在将密码哈希和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);
}
?>

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

谢谢!

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

还有另外两个问题需要解决:

  • 您不应该像使用PDO那样使用mysqli_connect_error()。正确的函数是$con->errorInfo()
  • 您使用连接设置定义了一些常量,但在PDO()调用中没有使用它们,而是重复这些值

使用

// 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移动了结果的光标。所以第一个调用提取第一行的1列,第二个调用将从第二行提取数据!