php - 如何使密码验证功能与 $_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";
}
}
?>
解决方案
在你的注册表格中有这样的东西,在这种情况下它使用 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!');
}
这只是展示如何使用函数本身,应用这个原则,你应该很高兴
推荐阅读
- html - 如何将图像的高度设置为与其宽度相同?
- python - 如何赋予 Python 对文件窗口的完全权限
- python - 我想播放一首歌,同时创建一个控制歌曲的 tkinter 窗口
- kotlin - 在 Intellij IDE 中编译 Kotlin 时无法删除缓存目录
- javascript - 如何编写 Jasmine 测试以覆盖 event.target.click
- django - 如何修复 django 模型实例
- html - 如何使用 TypeScript 换行
- javascript - 在 Jquery 或 Javascript 中模拟物理点击
- c++ - 发生段错误时不调用信号处理程序时?
- python - 如何保留具有唯一 ID 的嵌套列表?