doumei1926 2015-03-13 06:28
浏览 50
已采纳

验证PDO预处理语句中的password_hash()

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);

展开全部

  • 写回答

1条回答 默认 最新

  • dongzhaoshi8497 2015-03-13 06:40
    关注

    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(!empty($row)) {
            // check if the hashed row password
            if(password_verify($pass, $row['password'])) {
                // okay
            }
        } else {
            // not found
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部