I'm trying to use the bcrypt algorithm for hashing the passwords but I've ran into a couple of problems. First of all, I can't find the appropriate spot to check whether password_verify()
returns true.
$admin = $_POST['admin-user'];
$pass = $_POST['admin-pass'];
$password_hash = password_hash($pass, PASSWORD_BCRYPT);
if (isset($admin)&&isset($pass)&&!empty($admin)&&!empty($pass)) {
$admin_select = $link->prepare("SELECT `id` FROM `admins` WHERE `username` = :admin");
$admin_passwd = $link->prepare("SELECT `password` FROM `admins` WHERE `username` = :admin_pw");
$admin_passwd->execute(array(':admin_pw' => $admin));
$admin_pwd = $admin_passwd->fetch(PDO::FETCH_ASSOC);
if (password_verify($pass, $admin_pwd)){
if ($admin_select->execute(array(':admin' => $admin))) {
$res = $link->query('SELECT COUNT(*) FROM requests');
$query_num_rowz = $res->fetchColumn();
if ($query_num_rowz == 0) {
echo 'No records found';
} else if ($query_num_rowz > 0) {
$query = $link->prepare("SELECT id FROM admins WHERE username = :admin");
$query->execute(array(':admin' => $admin));
$admin_id = $query->fetch(PDO::FETCH_ASSOC);
$_SESSION['admin_id'] = $admin_id;
header('Location: index.php');
}
}
}
}
Second of all, I'm not sure this is the right way to select the user's password.
$admin_passwd = $link->prepare("SELECT `password` FROM `admins` WHERE `username` = :admin_pw");
$admin_passwd->execute(array(':admin_pw' => $admin));
$admin_pwd = $admin_passwd->fetch(PDO::FETCH_ASSOC);
Since you didn't put ->fetch
in a loop, the single invocation will return a single row of associative array. You must access the proper index first (in this case password
). Then compare the row value (at least if this is hashed already) inside the password_verify
with the user input. Rough example:
if(!empty($_POST['admin-user'] && !empty($_POST['admin-pass']))) {
$admin = $_POST['admin-user'];
$pass = $_POST['admin-pass'];
$admin_info = $link->prepare("SELECT `password` FROM `admins` WHERE `username` = :admin_user");
$admin_info->execute(array(':admin_user' => $admin));
$row = $admin_info->fetch(PDO::FETCH_ASSOC);
if($row && password_verify($pass, $row['password'])) {
// okay
} else {
// no such user/password
}
}