通过数据库更改用户密码

时间:2014-01-09 18:32:13

标签: php mysql passwords

您好我正在尝试创建一个用户可以更改密码的页面。当我输入当前密码并尝试更改密码时,似乎无法识别当前密码。我想知道它是不是因为我在另一个php文件的密码上使用了md5和salt1和salt2?

这是我的代码,非常感谢任何帮助和建议。

<?php
session_start();


require_once ("connect.php");
require_once 'functions/cleanstring.php';
require_once 'functions/encrypt.php';


$password = clean($db_server, $_POST['password']);
$newpassword = clean($db_server, $_POST['newpassword']);
$repeatnewpassword = clean($db_server, $_POST['repeatnewpassword']);


if ($_POST['submit'] == 'Change') {
    if ($password && $newpassword && $repeatnewpassword) {
        if ($newpassword == $repeatnewpassword) {
            if ($db_server) {

                mysqli_select_db($db_server, $db_database);
                $password = ($password);
                // check whether username exists 

                $query = "SELECT password FROM users WHERE password='$password'  AND         username='" . $_SESSION['username'] . "'";
                $result = mysqli_query($db_server, $query);

                if ($row = mysqli_fetch_array($result)) {
                    $newpassword = salt($newpassword);
                    $query = "UPDATE `users` SET `password`='$newpassword' WHERE    `username`='" . $_SESSION['username'] . "'";

                    mysqli_query($db_server, $query) or
                            die("Insert failed. " . mysqli_error($db_server));
                    $message = "<strong>You've changed your password!</strong>";

                    //require_once("db_close.php");
                    // Process further here 
                } else {
                    $message = "Please type the correct current password!";
                }
                mysqli_free_result($result);
            } else {
                $message = "Error: could not connect to the database.";
            }
            //require_once("db_close.php"); 
        } else {
            $message = "The new password and the 'Repeat New Password' must match!";
        }
    } else {
        $message = "Fill all fields.";
    }
}
?>

<?php
include_once("templates/open.php");
?> 


<form action='changepassword.php' method='POST'> 
    Password: <input type='password' name='password'><br /> 
    New Password: <input type='password' name='newpassword'><br /> 
    Retype New Password: <input type="password" name="repeatnewpassword"><br/>
    <input type='submit' name='submit' value='Change'> 
    <input name='reset' type='reset' value='Reset'> 
</form>

<?php echo $message; ?>
<p><a href='login.php'>Go back</a></p>
<?php
require_once 'templates/close.php';
?>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

是的,您必须salt用户输入的旧明文密码以进行检查,因为它已存储在数据库中。

您的代码应改为:

$password = ($password);

为:

$password = salt($password);

答案 1 :(得分:1)

使用md5()保存密码时,应将其与用户输入进行比较,如:

if(md5($password) == $db_password) ...

OR

if(salt($password) == $db_password) ...