md5哈希与数据库相比不适用php


md5 hash compare to database dont work php

我有这段代码用于登录测试,但遗憾的是,当与通过我的登录参数传递的登录数据匹配的一条记录(如果存在)进行比较时,我的哈希(md5)。(请参阅下面的代码)它总是返回$error="无效的用户名或密码",但当我试图删除md5哈希并使我的密码变平(无哈希)时,它就工作了,据说我不想出于安全目的而将我的密码扁平化。

//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;

不起作用,正如您从上面的参考代码行中看到的,它必须检查用户名是否包含数字、字母和下划线以外的内容,然后如果用户名包含数字、信件和下划线以外,则抛出错误,但它总是返回$error="用户名必须仅包含字母、下划线和数字!";

任何帮助、想法、线索都将不胜感激。非常感谢。

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