【发布时间】:2019-11-11 15:18:09
【问题描述】:
我有一个 HTML 格式的“创建新用户”表单,需要知道其中的某些部分需要验证和检查(PHP 或 javascript),以及最好的解决方法。
密码处理在 PHP 中完成,检查给定用户名是否可用或已存在于数据库中的代码也是如此。需要知道比较“密码”和“确认密码”字段的最佳位置,因为在 PHP 中对两者进行哈希处理时似乎很难做到。
if ($_SERVER["REQUEST_METHOD"] == "POST") { // If the form is submitted and by the method of post
$new_username = test_input($_POST['new_username']); // Set new_username to the new_username value from the form
$new_password = password_hash(test_input($_POST['new_password']), PASSWORD_DEFAULT); // Get the new_password from the form and hash it before passing to the variable
$confirm_password = password_hash(test_input($_POST['new_password_confirm']), PASSWORD_DEFAULT); // Get the confirm_password field from the form and hash it
$team = $_POST['new_team']; // Get the new_team field (doesn't need validation as it is a dropdown choice)
$username_valid = test_account_validity($newConnection, $new_username);
if ($username_valid) {
echo "";
}
if (hash_equals($new_password, $confirm_password)) {
echo "Passwords Match";
}
else {
echo "Passwords Dont Match";
}
}
function test_input($data) { // Function to remove spaces, slashes and special html characters before returning the valid data
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
当密码在散列之前相同(在两个表单字段中输入相同)但它说密码不匹配时,预期密码匹配输出。
编辑
与如何使用密码散列不同,因为这是关于将两个输入密码的散列相互比较,而不是将字符串与散列或散列进行比较以存储在数据库中。
【问题讨论】:
-
这不是
hash_equals所做的。再次链接密码哈希的基本介绍会有所帮助吗? -
@mario 如果你有一个真正有帮助的,我想我只是有点困惑。谢谢
-
为什么不简单地比较密码并在它们匹配后对其进行哈希处理?此外,您不应编辑用户密码。如果存在不允许的字符,最好通知用户密码无效,而不是更改密码。
-
@ich5003 这不会让它面临时间错误。在那种情况下,我仍然使用 hash_equals
-
我将使用以下行为: 1. 比较 POST[pass] 和 POST[pass_verify],如果它们匹配,则对其进行哈希处理并使用它。在您的登录方法中,您将使用 password_verify,因为 password_hash 使用盐,因此两次散列相同的密码不会产生相同的结果。见这里:php.net/manual/de/function.password-hash.php
标签: php hash passwords password-protection