md5 哈希与数据库比较不起作用 php

md5 hash compare to database dont work php

我有这个代码用于我的登录测试,但遗憾的是,我的哈希 (md5) 与一条记录(如果存在)进行比较,该记录与通过我的登录参数传递的登录数据相匹配。 (请参阅下面的代码)它总是 return $error = "Invalid username or password" 但是当我尝试删除 md5 散列并使我的密码平坦(none 散列)并且它工作时我应该出于安全目的,不想让我的密码变平。

//check if there is post request named username and password
if (isset($_POST['username']) || isset($_POST['password'])){
//check if username and password is empty
if ($_POST['username'] === "" || $_POST['password'] === ""){
$error = "Username or password must not be empty.";
} elseif (preg_match('`^[a-zA-Z0-9_]@{1,}$`', $_POST['username'])) {
// check if username contains other than number, letters and underscore
$error = "Username must only letters, underscore and numbers!";
exit;
}else{ //not empty then check in database
//filter username and password to avoid sql injections
$username = htmlspecialchars(stripslashes($_POST['username']));
$password = htmlspecialchars(stripslashes($_POST['password']));
$password = md5($password);
$sql = "SELECT id from user WHERE username='$username' and password='$password'";
 //checking if the username is available in the table
$result = mysqli_query($db,$sql);
$count_row = $result->num_rows;
if ($count_row == 1) {
$_SESSION['login'] = true;
header('location: home.php');
exit;
}else{
        $error = "Invalid username or password";
} //end of else if theres no record found.
} //end of else isset username and password
}//end of isset username and password

还有这一行

} elseif (preg_match('`^[a-zA-Z0-9_]@{1,}$`', $_POST['emailusername'])) {
// check if username contains other than number, letters and underscore
echo "Username must only letters, underscore and numbers!";
exit;

也不起作用,正如您从上面的参考代码行中看到的,它必须检查用户名是否包含数字、字母和下划线以外的内容,如果用户名包含数字、字母和下划线以外的内容,则抛出错误,但它总是 return $error="Username must only letters, underscore and numbers!";

任何帮助、想法和线索将不胜感激。谢谢!

不再推荐md5 hash 安全了。如果您仍然喜欢 md5 散列,那么正如我在您的代码中看到的那样(在 md5 散列的行中)似乎没有问题。检查您的数据库并比较您的密码输出(md5 哈希)。