无法与数据库中的md5密码进行比较

时间:2016-07-17 11:36:17

标签: php sql md5 password-encryption

signup.php

$password_unencrypted = $_POST['passwd'];

$password=md5($password_unencrypted);

$query = "INSERT INTO Customers (firstname, lastname, username, password, " .     "gender,mobile,email) " .     "VALUES ('$first_name', '$last_name', '$user_name', '$password', " .     " '$gender','$mobile','$email')";

的login.php

$username=$_POST['username'];
$password=md5($_POST['password']); 

 $sql = ("select * from Customers where username='".$username."' and password='".$password."'") or die('Error connecting to MySQL server.');

     $query = mysqli_query($con,$sql);

     $result=mysqli_fetch_row($query);



         if($result)
         {             
           $_SESSION['username']=$username;
           header('location:home.html');           
         }
         else
         {
             echo md5($_POST['password']);
             echo 'Your entered username or password is incorrect';
         }

在上面的注册和登录代码中,我正在应用md5进行密码存储

我在数据库中检查了md5密码是否存储正确但是没有正确检索(我认为)

尝试登录页面失败

仅供参考:echo md5($ _ POST ['password']);在Login.php中显示存储在数据库中的相同密码

1 个答案:

答案 0 :(得分:1)

这是如何修复您的login.php代码

你完全检查错了你需要首先检查查询是否成功运行然后检查返回的行是否大于0表示用户名是正确的我们继续密码检查如果一切正常我们开始会话假设你有如果不在$_SESSION['username'] = $username;之前添加,则会在页面顶部显示session_start() 查看password_hash()password_verify()

的手册

在register.php上修改将密码保存到数据库中 $password = md5($_POST['password']);$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    <?php
if isset($_POST['submit']) {
$username= mysqli_real_escape_string($con, trim($_POST['username']));
$password = trim($_POST['password']); // no need to sanitize the password 

 $sql = "select * from Customers where username = '" .$username."' "; // you don't need or Die() it's just a string
     if ($result = mysqli_query($con,$sql)) //check if the Query succeeded running
     {
     $count = mysqli_num_rows($result);
         if($count > 0 ) 
         { // if username exists we proceed to checking password
        $fetch = mysqli_fetch_assoc($result);
        $hashedpassword = $fetch["password"];

            if ( password_verify($password, $hashedpassword) ) 
            {  //checking password  
           $_SESSION['username']=$username;
           header('location:home.html'); 
            exit;
            }else {
                    echo "incorrect username or password"; // you don't want to tell him that the username is fine but the password is not correct 
             }                      
            } else {
             echo "incorrect username or password";
         }       
     } else {
             echo 'Query failed to run';
         }
}            
?>