密码哈希不适用于MySQL

时间:2018-05-29 02:35:55

标签: php mysql

我整天都在这里看了所有已回答的问题并且还在线查看了有关密码哈希的教程。看起来好像我做得对,它在数据库中哈希密码但是当我去登录时它告诉我密码不正确。这是脚本,非常感谢任何帮助。

的login.php

if (isset($_POST['username'])){
//escapes special characters in a string
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = $_REQUEST['password'];
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$hash = $row['password'];
if (password_verify($password, $hash)) {
    $_SESSION['username'] = $username;
    // Redirect user to index.php
    $position = $row['position'];
    if ( $position == "freelancer" ){
    header("Location: ../freelancer/index.php");
    }
    elseif ($position == "employer"){
    header("Location: ../employer/index.php");
    }
}
else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
".$hash." " .$password. "
<br />Click here to <a href='login.php'>Login</a>
</div>";

Register.PHP(哈希密码的代码片段)

   //BEGINNING CODE HERE
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$sql_u = "SELECT username FROM users WHERE username='$username'";
$sql_e = "SELECT email FROM users WHERE email='$email'";
$res_u = mysqli_query($con, $sql_u);
$res_e = mysqli_query($con, $sql_e);
if (mysqli_num_rows($res_u) > 0) {
$name_error = "Sorry... username already taken";
}
else if(mysqli_num_rows($res_e) > 0){
$email_error = "Sorry... email already taken";
}
else{
$query = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$hashPassword')";
$results = mysqli_query($con, $query);
mkdir("../profilePics/" . $username);
echo 'You Have Registered Successfully!<br>
To Login Go To <a href="login.php">Our Login Page</a>
';
exit();
}
}
?>

我知道这段代码可能有更多错误但我只对基本了解密码散列感兴趣。

1 个答案:

答案 0 :(得分:0)

$password = mysqli_real_escape_string($con,$password);

您的密码现在已转义,并且肯定不会与哈希相匹配。 最好删除此行并寻找更好的方法来确保字符串是安全的。

逃跑是什么意思? 如果您的密码包含&#34; 它会变成\&#34;

FYI Should I mysql_real_escape_string the password entered in the registration form?