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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64