Hi I am trying to create a page where my users can change their password. When I type in the current password and try to change it, it seems to be not recognising the current password. I was wondering wether it was because I have used md5 and salt1 and salt2 on the password on another php file?
Here is my code, any help and advice would be much appreciated.
<?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>
Yes, you have to salt
the old plain-text password as entered by the user as well to do the check, because it's stored salted in the database.
Your code should be changed from:
$password = ($password);
to:
$password = salt($password);
When you save your password using md5()
, you should compare it with user input like :
if(md5($password) == $db_password) ...
OR
if(salt($password) == $db_password) ...