Jump to content

Password Reset Not Working


Go to solution Solved by paddy_fields,

Recommended Posts

It's just a notice, not an error. It's because you haven't defined $securityUser.

 

But changing $_POST['pw0'] to $_POST['p'] wouldn't have caused that. Did you change anything else?

 

Check if the password has been updated and if you can log in.

Edited by paddyfields
  • Replies 53
  • Created
  • Last Reply

Top Posters In This Topic

Yip check that as well, no change on the password. I am still able to login with the old password.

 

I also changed the button, as mac_gyver mentioned, the button points specifically to the register function. I did how ever create a new function specifically for the reset as the fields on the reset form and the register form that it points to are different.

 

so

if (strcmp($_POST['password'],$_POST['confirmpwd']) != 0 || trim($_POST['password']) == '')  would also have changed, it was originally

if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '') .

 

Also anywhere else that I had pw0 / pw1 it would of changed to password / confirmpwd

Edited by SalientAnimal

Well if the old password still works then it isn't updating the database at all. So we're trying to solve the wrong problem.

 

You need to debug your code to work out why the new password is not being inserted into the database.

Originally the password was updating, which is why I really have no idea what the problem is. Before I made all the changes I've been making it was updating and I even did checks by un-hashing etc. Then trying to login with the old login details and the new login details. The problem then was that neither was allowing me to log in.

Debug.

 

On the part of your script where there is the SQL connection to your database , where the new password should be updated, echo out each of the values that should have been inserted. You need to see why the SQL update isn't working.

 

Once you've found which variable is empty (which I'm guessing is the cause), work your way back and find out why.

i'm wondering why you removed the $salt value from being the 4th parameter to the updateUserPassword() call? if you didn't also move the generation of that value into the updateUserPassword() function itself, your code is not going to work.

This is the updateUserPassword() function as I have t now:

function updateUserPassword($password, $user_id, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key ,$user_id) === false) return false;
 		if (empty($error_msg)) {
        // Create a random salt
        $salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
		}	
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ?, salt = ? WHERE id = ?"))
    {
        $password = hash('sha512', $password . $salt);
        $stmt->bind_param('ssi', $password, $salt, $user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}

You posted your entire code a few times on this thread so you can always just revert to that :). But that is why you should backup frequently.

 

As I said before, debug.

function updateUserPassword($password, $user_id, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key ,$user_id) === false) return false;
 		if (empty($error_msg)) {
        // Create a random salt
        $salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

    // Debug
    echo "password = ".$password;
    echo "<br>";
    echo "user id = ".$user_id;
    echo "<br>";
    echo "security key = ".$security_key;
    echo "<br>";
    echo "salt = ".$salt;
    echo "<br>";

    exit;

}


When you submit the new password, what does this output?

Sorry there was a syntax error in my code

function updateUserPassword($password, $user_id, $security_key)
{
    global $mysqli;
    if (checkEmailkey($security_key ,$user_id) === false) return false;
 		if (empty($error_msg)) {
        // Create a random salt
        $salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
      }

    // Debug
    echo "password = ".$password;
    echo "<br>";
    echo "user id = ".$user_id;
    echo "<br>";
    echo "security key = ".$security_key;
    echo "<br>";
    echo "salt = ".$salt;
    echo "<br>";

    exit;

}


Looking through your code, why have you changed 'pw0' and 'pw1' to 'password' and 'confirmpwd'? This may be having an effect on another script that's being included, and hence causing your script to fail.

I changed 'pw0' and 'pw1' to 'password' and 'confirmpwd' because it was one of the suggestions made by mc_gyver. I did however look through all my scripts and replace all instances where 'pw0' and 'pw1' appear with  'password' and 'confirmpwd'. I did a copy / paste of the password section from my registration page.

 

I will add you debug again and give feedback.

Still getting the same error message:

Password Recovery

Welcome back, 
Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 239
 TestAgent2.

In the fields below, enter your new password.
The new passwords must match and must not be empty. 

New Password


Confirm Password

Edited by SalientAnimal

I think what might be best is if I start everything from scratch on Monday, and then work through it piece by piece.

 

Not sure if it will be better to close this thead off till then, or to leave it open and then to just post the updated code here and continue trouble shooting from there? What would you suggest?

Well that means that you are meeting the conditions of the if statement, and therefore your function is not being called...

 if (strcmp($_POST['password'],$_POST['confirmpwd']) != 0 || trim($_POST['password']) == '')
            {
                $error = true;
                $show = 'recoverForm';
            } else {
                $error = false;
                $show = 'recoverSuccess';
                updateUserPassword($_POST['p'], $_POST['user_id'], $_POST['security_key']);
            }

Your 'recoverForm' is being shown.

 

This means that when you post your form, either $_POST['password'] or $_POST['confirmpwd'] are NULL.

 

So your form isn't working.

 

I think that it may be your onclick that's the problem... it should be onClick="return resetformhash(this.form,this.form.password,this.form.confirmpwd)

Actually, you were missing a closing braket in your form.

 

Try this:


<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
  <div class="fieldGroup">
  <label class="grey" for="password">Password:
  </label>
  <input class="field" type="password" name="password" id="password"/>
  <br>

  <label class="grey" for="confirmpwd">
    Confirm Password:
  </label>
  <input class="field" type="password" name="confirmpwd" id="confirmpwd"/>
  <br>
   
  <input type="hidden" name="subStep" value="3" />
  <input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
  <input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>"/>
  <div class="fieldGroup">
    <input class="bt_login" type="button" value="Reset" onClick="return resetformhash(this.form,this.form.password,this.form.confirmpwd);" style="margin-left: 150px;"/>
  </div>
  <div class="clear">
  </div>
</form>
</div>
Edited by paddyfields

Tried the change in code you supplied, but still the same.

 

Really think I should maybe start from scratch with the original source code.

Password Recovery

Welcome back, 
Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 239
 TestAgent2.

In the fields below, enter your new password.
The new passwords must match and must not be empty.	

Password: 
Confirm Password: 

Ok, I have restarted this from scratch using the original source. Hopefully if we work through all the errors step by step we will be able to resolve the problem.

 

Is it best to continue in this thread? Or should I start a new thread?

 

From where I am now I am getting the following two messages (these messages only appear if I submit a blank answer to the security question):

 

Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 134

Notice: Undefined index: in C:\htdocs\includes\functions.php on line 392

 

When entering an incorrect answer to the security question I get the following:

 

Notice: Undefined index: in C:\htdocs\includes\functions.php on line 392

 

LINE 134:

<div class="field"><?= getSecurityQuestion($securityUser); ?></div>

LINE 392:

 

return $questions[$security_q];

The security question on line 392 is saved in the database table as a number, and it then identifies the question. This is the entire piece of code to that function:

function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
        return $questions[$security_q];
    } else {
        return false;
    }
}



 

Another problem that I know I will pick up later is the fact that my passwords are stored as sha512, where as the original source script uses md5. What I have done in the previous attempts is to replace "md5(" with "hash('sha512',".

Edited by SalientAnimal

The notices are telling you what the problem is, and there isn't enough code posted here to solve this.

 

My best advice is to take the notices into account and try and solve them one by one - think logically about what you're expecting the code to do.

 

For example, Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 134, means that $securityuser is empty, so analyse/debug your code and try and find why that variable is not being set.

 

 
 

Thanks for that. So with my limited knowledge, what I do understand is the variable needs to be set. What I don't understand though is that if I go through the entire form and complete all the fields "Correctly" there are no error messages. The form displays the user name where needed, security question as needed etc...

 

Why is it though that if I submit a field incorrectly, it seems to all of a sudden "forget" the set variable?

 

Here is the entire code of the form:

<?php
include_once 'db_connect.php';
include_once 'functions.php';
include_once 'formatting_includes.php';	
sec_session_start();
if (login_check($mysqli) == true) 
	{
    $logged = 'in';
	} 
	


$show = 'emailForm'; //which form step to show by default
if(!isset($_SESSION['lockout']))
   $_SESSION['lockout'] = false;
if (isset($_SESSION['lockout']) && $_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))

{
    $_SESSION['lockout'] = false;
    $_SESSION['badCount'] = 0;
}
if (isset($_POST['subStep']) && !isset($_GET['a']) && $_SESSION['lockout'] != true)
{
    switch($_POST['subStep'])
    {
        case 1:
            //we just submitted an email or username for verification
            $result = checkUNEmail($_POST['username'],$_POST['email']);
            if ($result['status'] == false )
            {
                $error = true;
                $show = 'userNotFound';
            } else {
                $error = false;
                $show = 'securityForm';
                $securityUser = $result['id'];
            }
        break;
        case 2:
            //we just submitted the security question for verification
            if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
            {
                $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                if ($result == true)
                {
                    //answer was right
                    $error = false;
                    $show = 'successPage';
                    $passwordMessage = sendPasswordEmail($_POST['user_id']);
                    $_SESSION['badCount'] = 0;
                } else {
                    //answer was wrong
                    $error = true;
                    $show = 'securityForm';
                    $securityUser = $_POST['user_id'];
                    $_SESSION['badCount']++;
                }
            } else {
                $error = true;
                $show = 'securityForm';
            }
        break;
        case 3:
            //we are submitting a new password (only for encrypted)
            if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../login.php");
            if (strcmp($_POST['password'],$_POST['confirmpwd']) != 0 || trim($_POST['password']) == '')
            {
                $error = true;
                $show = 'recoverForm';
            } else {
                $error = false;
                $show = 'recoverSuccess';
                updateUserPassword($_POST['user_id'],$_POST['password'],$_POST['security_key']);
            }
        break;
    }
}

elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
    $show = 'invalidKey';
    $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
    if ($result == false)
    {
        $error = true;
        $show = 'invalidKey';
    } elseif ($result['status'] == true) {
        $error = false;
        $show = 'recoverForm';
        $securityUser = $result['user_id'];
    }
}
if (isset($_SESSION['badCount']) && ($_SESSION['badCount'] >= 3))
{
    $show = 'speedLimit';
    $_SESSION['lockout'] = true;
    $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
}
?>

	 


<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header"></div>
<div id="page">

<?php switch($show) {
    case 'emailForm': ?>
    <h2>Password Recovery</h2>
    <p>You can use this form to recover your password if you have forgotten it. Because your password is securely encrypted in our database, it is impossible actually recover your password, but we will email you a link that will enable you to reset it securely. Enter either your username or your email address below to get started.</p>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label for="username">Username</label><div class="field"><input type="text" name="username" id="username" value="" maxlength="20"></div></div>
        <div class="fieldGroup"><label>- OR -</label></div>
        <div class="fieldGroup"><label for="email">Email</label><div class="field"><input type="text" name="email" id="email" value="" maxlength="255"></div></div>
        <input type="hidden" name="subStep" value="1" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
    <?php break; case 'securityForm': ?>
    <h2>Password Recovery</h2>
    <p>Please answer the security question below:</p>
    <?php if ($error == true) { ?><span class="error">You must answer the security question correctly to receive your lost password.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup">
			<label>Question</label>
				<div class="field"><?= getSecurityQuestion($securityUser); ?></div>
		</div>
			
        <div class="fieldGroup">
			<label for="security_a">Answer</label>
				<div class="field"><input type="text" name="security_a" id="security_a" value="" maxlength="255"></div>
		</div>
        <input type="hidden" name="subStep" value="2" />
        <input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
 
     
     <?php break; case 'userNotFound': ?><br>    
	 <h2>Password Recovery</h2><br>    
	 <p>The username or email you entered was not found in our database.<br /><br />
	 <a href="?">Click here</a> to try again.</p><br>    
	 <?php break; case 'successPage': ?><br>    
	 <h2>Password Recovery</h2><br>    
	 <p>An email has been sent to you with instructions on how to reset your password. 
	 <strong>(Mail will not send unless you have an smtp server running locally.)</strong>
	 <br /><br /><a href="../login.php">Return</a> to the login page. </p><br>    
	 <p>This is the message that would appear in the email:</p><br>    
	 <div class="message"><?= $passwordMessage;?></div><br>    
	
	
	 <?php break;
case 'recoverForm': ?>
    <h2>Password Recovery</h2>
    <p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
    <p>In the fields below, enter your new password.</p>
    <?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label for="password">New Password</label><div class="field"><input type="password" class="input" name="password" id="password" value="" maxlength="20"></div></div>
        <div class="fieldGroup"><label for="confirmpwd">Confirm Password</label><div class="field"><input type="password" class="input" name="confirmpwd" id="confirmpwd" value="" maxlength="20"></div></div>
        <input type="hidden" name="subStep" value="3" />
        <input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
        <input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
    <input class="bt_login" type="button" value="Reset" onClick="return resetformhash(this.form,this.form.password,this.form.confirmpwd);" style="margin-left: 150px;"/>
        <div class="clear"></div>
    </form>
    <?php break; case 'invalidsecurity_key': ?>
    <h2>Invalid security_key</h2>
    <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; case 'recoverSuccess': ?>
    <h2>Password Reset</h2>
    <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; case 'speedLimit': ?>
    <h2>Warning</h2>
    <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php break; }
    ob_flush();
    $mysqli->close();
?>


<!--PAGE CONTENT-->
</div>
</body>
</html>


Password Form Functions:

function checkUNEmail($username,$email)
{
    global $mysqli;
    $error = array('status'=>false,'user_id'=>0);
    if (isset($email) && trim($email) != '') {
        //email was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($email));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } elseif (isset($username) && trim($username) != '') {
        //username was entered
        if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
        {
            $stmt->bind_param('s',trim($username));
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
        } else { return $error; }
    } else {
        //nothing was entered;
        return $error;
    }
}



function getSecurityQuestion($user_id)
{
    global $mysqli;
    $questions = array();
    $questions[0] = "What is your mother's maiden name?";
    $questions[1] = "What city were you born in?";
    $questions[2] = "What is your favorite colour?";
    $questions[3] = "What year did you graduate from High School?";
    $questions[4] = "What is your pet's name?";
    $questions[5] = "What is your favorite model of car?";
    if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($security_q);
        $stmt->fetch();
        $stmt->close();
        return $questions[$security_q];
    } else {
        return false;
    }
}
 
function checkSecAnswer($user_id, $security_a)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
    {
        $security_a = strtolower($security_a);
        $stmt->bind_param('is',$user_id, $security_a);
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->close();
        if ($numRows >= 1) { return true; }
    } else {
        return false;
    }
}




function sendPasswordEmail($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username, $email, $password);
        $stmt->fetch();
        $stmt->close();
        $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
        $expDate = date("Y-m-d H:i:s",$expFormat);
        $salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));		
        $security_key = hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . $salt);
        if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
        {
            $stmt->bind_param('iss',$user_id, $security_key, $expDate);
            $stmt->execute();
            $stmt->close();
            $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://jhbvcstracking/resetpwd.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
            $message = "Dear $username,\r\n";
            $message .= "Please visit the following link to reset your password:\r\n";
            $message .= "-----------------------\r\n";
            $message .= "$passwordLink\r\n";
            $message .= "-----------------------\r\n";
            $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
            $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
            $message .= "Thanks,\r\n";
            $message .= "-- Our site team";
            $headers .= "From: Our Site <webmaster@oursite.com
			
<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>> \n";
            $headers .= "To-Sender: \n";
            $headers .= "X-Mailer: PHP\n"; // mailer
            $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; // Reply address
            $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>\n"; //Return Path for errors
            $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
            $subject = "Your Lost password";
            @mail($email,$subject,$message,$headers);
            return str_replace("\r\n","<br/ >",$message);
        }
    }
}


function checkEmailKey($security_key,$user_id)
{
    global $mysqli;
    $curDate = date("Y-m-d H:i:s");
    if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
    {
        $stmt->bind_param('sis',$security_key, $user_id, $curDate);
        $stmt->execute();
        $stmt->execute();
        $stmt->store_result();
        $numRows = $stmt->num_rows();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        $stmt->close();
        if ($numRows > 0 && $user_id != '')
        {
            return array('status'=>true,'user_id'=>$user_id);
        }
    }
    return false;
}
 
function updateUserPassword($user_id, $password, $security_key)
{
    global $mysqli;
    if (checkEmailsecurity_key($security_key,$user_id) === false) return false;
    if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
    {
        $password = hash('sha512',trim($password) . $salt);
        $stmt->bind_param('si',$password,$user_id);
        $stmt->execute();
        $stmt->close();
        $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
        $stmt->bind_param('s',$security_key);
        $stmt->execute();
    }
}
 
function getUserName($user_id)
{
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
    {
        $stmt->bind_param('i',$user_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($username);
        $stmt->fetch();
        $stmt->close();
    }
    return $username;
}

It's not 'forgetting' anything. When you send the form, the data is being sent to the same page so all of the variables are effectively cleared and rely on the POST data you have just sent in your form. Below I've tried to explain what your code is doing and what the notices mean.

 

Two questions; what happens when you enter your security question correctly, and when you answer it incorrectly does a new question appear?

//we just submitted the security question for verification


            if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
            {
                $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                if ($result == true)
                {
		  //RULE 1	
                    //answer was right
                    $error = false;
                    $show = 'successPage';
                    $passwordMessage = sendPasswordEmail($_POST['user_id']);
                    $_SESSION['badCount'] = 0;
                } else {
                 //RULE 2
                    //answer was wrong
                    $error = true;
                    $show = 'securityForm';
                    $securityUser = $_POST['user_id'];
                    $_SESSION['badCount']++;
                }
            } else {
            //RULE 3 
                $error = true;
                $show = 'securityForm';
            }

Rule 1: A security question answer was entered, and was correct. So the sendPasswordEmail() function is called.

 

Rule 2. A secrurity question answer was entered, and was wrong. The security form is shown again, and $securityUser is set to $_POST[‘user_id’]

 

Rule 3. No security answer was entered, so $securityUser is not set. Hence the variable notice.

Edited by paddyfields

 Firstly, sorry for taking so long to reply, I was stuck in a meeting for the remainder of the day.

 

Two questions; what happens when you enter your security question correctly, and when you answer it incorrectly does a new question appear?

 

The security question is pulled from the database. On registration the user is asked to select a security question, so they will always get the same question. When answering the question correctly, the user is displayed a link onscreen that is hashed.

 

If I however answer the question incorrectly, the form displays as per-usual, except this line is added:

"You must answer the security question correctly to receive your lost password."

 

If I try submitting a blank answer:

The security question is removed, but the form is still displayed, with this message "You must answer the security question correctly to receive your lost password."

And these messages are displayed:

 

Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 134

Notice: Undefined index: in C:\htdocs\includes\functions.php on line 392

 

At this point, not matter if I fill in a answer on the second attempt, it can not submit it correctly. I am assuming this is because it is not longer storing the "securityUser"?

 

 

I'm trying the step-by-step approach this time with the form, to identify and fix any errors before moving onto the next step.

 

Would it be advisable to then, on rule 3, maybe add an error message rather than un-setting the security user?

Edited by SalientAnimal

If you add $securityUser = $_POST['user_id']; to rule 3, then yes that will deal with the notice and I would imagine it will display the security question again.

 

So everything works as expected when you enter the answer correctly or incorrectly on the first form submission? It's just on the second attempt that the problems occur?

 

I agree, I think it something to do with $securityUser, but this is what you need to then test!

 

After <div id="page"> put something like <h1>USER ID: <?php echo $securityUser; ?></h1> and the  see if it is displayed once you submit the form for a second time.

 

If it doesn't, then you know for sure and can try and work out why.

 

Just as a quick attempt, in your form change <input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
to <input type="hidden" name="user_id" value="<?php echo $securityUser; ?>" />
 

 

 

.
 

Edited by paddyfields

Ok, that seems to be working now. I updated Rule 3 to be:

else {
                $error = true;
                $show = 'securityForm';
                $securityUser = $_POST['user_id'];					
            }

I also changed the below as you suggested. Should I change this back now, or leave as is.

 

Just as a quick attempt, in your form change <input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
to <input type="hidden" name="user_id" value="<?php echo $securityUser; ?>" />

 

So at this point of the form, I am given the security link, which I can then follow to the form where I change my password. However, if I copy the link into a new window, rather than just clicking on the link displayed (Remember I'm not e-mailing the link, I'm just displaying it to them onscreen at the current moment) I get a HTTP 404 Not Found Error.

 

I then complete the form with the new desired password, and on clicking submit I get the security user notice again 

Notice: Undefined variable: securityUser in C:\htdocs\includes\resetpwd.php on line 166

This is line 166

    <p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>

I am also still able to login with the old password, which would mean that the able was not updated.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.