这段代码总是说旧密码不正确?

时间:2015-10-01 17:51:39

标签: php html database mysqli

我正在尝试创建一个密码更改工具,要求用户输入旧密码,新密码并确认新密码。如果旧密码与数据库匹配,则会更新密码。否则说明不正确的旧密码。但是这段代码总是说旧密码不正确。有人在这段代码中找到了错误吗?我正在使用md5程序在用户注册时存储密码。它与此有什么关系吗?请原谅我冗长的代码。我还是个初学者。谢谢你:) HTML

<div class="col-sm-4">
   <h1 class="register-title">Change Password</h1>
       <form action="<?=$_SERVER['PHP_SELF']?>" method="post" class="register">
       <input type="password" name="oldpassword" class="register-input" placeholder="Enter Old Password">
       <input type="password" name="newpassword" class="register-input" placeholder="Enter New Password">
       <input type="password" name="password2" class="register-input" placeholder="Confirm New Password">
       <input type="submit" name="submit1" value="Update Password" class="register-button">
       </form>
 </div>  

PHP

<?php
if (isset($_POST['submit1'])) {
    $oldpassword=$_POST['oldpassword'];
    $newpassword=$_POST['newpassword'];
    $password2=$_POST['password2'];
    //$password=md5($password);

    $connect = mysqli_connect('localhost', 'root', '', 'blood'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
    $query12 = "select password from users WHERE uid = '$uid'";
    $query13 = "UPDATE users SET password='$newpassword' WHERE uid = '$uid'";
    $result12=mysqli_query($connect,$query12) or die('Error, query failed');
    if (mysqli_num_rows($result12) == 0) {
        echo 'Database is empty <br>';
    } elseif ($result12) {
       while ($row = mysqli_fetch_array($result12)) {
           if ($oldpassword == $row["password"]) {
               $result13=mysqli_query($connect,$query13) or die('Error, query failed');
           } else {
               echo "incorrect old password";
           }
       }
    }
}?>

1 个答案:

答案 0 :(得分:1)

如果您说在存储密码时使用md5,那么您如何看待存储的值password?当然是哈希值。

因此,如果$row["password"]具有散列值且您的$_POST['oldpassword'] 哈希值,那么您期望什么?

比较的正确方法应该是:

if (md5($oldpassword) == $row["password"])

顺便说一句,使用md5 不安全