PHP准备好的语句登录 [英] PHP Prepared statement login
问题描述
我正在将密码哈希和SQL注入防御添加到我的Login系统中.目前,我遇到了一个错误.
I'm in the process of adding password hashing and SQL injection defenses into my Login system. Currently, I've ran into an error.
<?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);
}
?>
在上面的代码中,当我输入有效的用户名和密码时,系统将输出"Invalid". if语句中的password_verify()可能是错误的(因为如果删除它,则我成功登录了).我确定我已经正确完成了查询的准备,绑定和执行?有人知道它为什么这样做吗?
In the above code, when I enter a valid username and password, the system prints out "Invalid". It could be a error in the password_verify() in the if statement(because if I remove it, I login successfully). I'm pretty sure I've done the preparing, binding and execution of the query properly? Does anyone know why it is doing this?
谢谢!
推荐答案
使用
// 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移动结果的光标.因此,第一次调用将提取第一行的第一列,第二次调用将从SECOND行提取数据!
Because fetchColumn moves cursor of result. So first call extracts 1 column of first row, and second call will extract data from SECOND row!
这篇关于PHP准备好的语句登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!