drmet46444 2017-07-20 16:18
浏览 88
已采纳

使用password_verify登录用户

I'm creating a back end to my website and running into issues with the login user part.

The user registration into the database is made with the password_hash function using the code below:

UserReg.php :

<?php

require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);

if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}

$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);

add_user($mysqli,$username, $token);

function add_user($mysqli,$username, $token) {
    $query = $mysqli->prepare("INSERT INTO users(username, password) VALUES 
    (?,?)");

$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();

if(!$result) {
    die($mysqli->error);
}
$query->close();
}

My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.

Login.php

<?php

include 'db.php';

$username = $_POST['user'];
$pwd = $_POST['password'];

$sql = "SELECT password FROM users WHERE username = ?";

$stmt = $mysqli->prepare($sql); 
$stmt->execute();
$stmt->bind_result($pass);

while ($result = $stmt->num_rows()) {
    if($stmt->password_verify($pwd, $result)) {    
        echo "Your username or password is incorrect";
    } else {
        header("Location: Menu.php");  
    }
}

What am i missing?

Appreciate your help.

  • 写回答

1条回答 默认 最新

  • douan6815 2017-07-20 16:33
    关注

    I think you need to take a look at password_verify how it works.

    $username = $_POST['user'];
    $pwd = $_POST['password'];
    
    $sql = "SELECT username, password FROM users WHERE username = ?";
    
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->bind_result($username, $password);
    $stmt->store_result();
    if ($stmt->num_rows == 1) { //To check if the row exists
      if ($stmt->fetch()) { //fetching the contents of the row
        if (password_verify($pwd, $password)) {
          $_SESSION['username'] = $username;
          echo 'Success!';
          exit();
        } else {
          echo "INVALID PASSWORD!";
        }
      }
    } else {
      echo "INVALID USERNAME";
    }
    $stmt->close(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了