首页 > 解决方案 > 如何使密码验证功能与 $_POST 一起使用

问题描述

我想制作一个带有密码验证的登录系统。我已使用密码默认值加密了我的密码。我还将哈希存储在数据库中。现在我想用密码验证来做一个登录系统,但是这个函数总是重新返回一个 true 的值。有人可以解释为什么吗?有人可以解释一下如何使用 $_POST 进行密码验证吗?

哈希码

<?php
/**
 * Created by PhpStorm.
 * User: jbosma
 * Date: 24/07/2018
 * Time: 23:21
 */
include_once "dbconnection.php";
if (isset($_POST["submit"])) { // send the input
    $username = $_POST["username"]; // post the input username
    $password = $_POST["password"]; // post the input password
    $conn = new PDO("mysql:host=localhost;dbname=loginapp", $user, $pass); // database connection
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // error mode
    $hash = PASSWORD_HASH($password, PASSWORD_DEFAULT); // make $hash so you can give that to your password in the query
    $sql = "INSERT INTO users (username, password) VALUES ('".$username."','".$hash."')"; // insert the username and the password that will be hashed
    $conn->exec($sql); // excecute the query above
    header('location: register.php'); // after you submit it redirects to login.php




}

密码验证代码

<?php
/**
 * Created by PhpStorm.
 * User: jbosma
 * Date: 27/07/2018
 * Time: 12:11
 */
include_once "dbconnection.php";
if (isset($_POST["submit"])) { // send the input
    $username = $_POST["username"]; // post the input username
    $password = $_POST["password"]; // post the input password

    $hash = $password; // hash from password
    if (password_verify($_POST["password"], $hash)) {
        echo "Welcome";
    } else {
        echo "Wrong Password";
    }
}
?>

标签: phpmysqlpassword-hash

解决方案


在你的注册表格中有这样的东西,在这种情况下它使用 BCRYPT。这只是显示 password_hash 函数

登记

// Other code  leading up to this..
....
//
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));


  $insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
  $stmt = $pdo->prepare($insrt);


  $stmt->bindValue(':username', $username);
  $stmt->bindValue(':password', $passHash);


  $result = $stmt->execute();

  if($result){
// Do whatever you want

登录

// Other code  leading up to this..
....
//
$validPassword = password_verify($pass, $user['password']);

    if($validPassword){

        $_SESSION['user_id'] = $user['username'];
        $_SESSION['logged_in'] = time();

        // redirects in this case
        header( "Location: /wherever.php" );
        die();

    } else{
        die('Wrong password!');
    }

这只是展示如何使用函数本身,应用这个原则,你应该很高兴


推荐阅读