Login fails after password reset

Here is the code for inserting a new user on registration

 $passwordHash = password_hash($password, PASSWORD_BCRYPT,ARRAY("COST"=> 12));
 
				 $result = add_user($firstname, $lastname, $email, $username, $passwordHash);

Here is the function:

 function add_user($firstname, $lastname, $email, $username, $password)
				{	
					global $db;
					
					try
					{
					 $sql = "
				     INSERT INTO users 
					 (firstname, lastname, email, username, password, reg_date)
					 VALUES
					 (:firstname, :lastname, :email, :username, :password, NOW())";		

					 $stmt = $db->prepare($sql);
					 $stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
					 $stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
					 $stmt->bindParam(':email', $email, PDO::PARAM_STR);
					 $stmt->bindParam(':username', $username, PDO::PARAM_STR);
					 $stmt->bindParam(':password', $password, PDO::PARAM_STR);
					 $stmt->execute();
		
					return true;	
				   }
					catch(Exception $e) 
				   { 
					return false;        
				   }
				}

Here is the code for updating password:

 $passwordHash = password_hash($password, PASSWORD_BCRYPT, ARRAY("COST"=> 12));
         $result = update_user_password($passwordHash, $userEmail);

And here is the function:

function update_user_password($newpwdHash, $email)
{
    global $db;
	 
	try
	  {
	   $sql = "UPDATE users
			   SET password =:newpwdHash
			   WHERE email=:email";
	   $stmt = $db->prepare($sql);
	   $stmt->bindParam(':newpwdHash', $newpwdHash, PDO::PARAM_STR);
	   $stmt->bindParam(':email', $email, PDO::PARAM_STR);
	   $stmt->execute();
	   return true;
	  }
	catch(Exception $e)
	  {
	   return false; 
	  }
 

 }// End function

After updating password, on login I get an error, incorrect username / password

Where is the problem if I hash the password exactly the same way ?

What we are missing here is the login code that gives you the error.

I’m going to guess that $password doesn’t contain exactly what you think it does. What is all the code, less any database connection credentials, for any page involved in the password form and form processing.

Another possibility is code that is being requested twice or code is redirecting but doesn’t have an exit/die statement to stop php execution, and there’s some code changing the stored hash value again.

Two slightly off-topic comments if I may:

If you’re inserting the current date/time when you add a user, set the default for that column to CURRENT_TIMESTAMP in your table definition and leave it out of the query altogether.

Global variables make my teeth itch. Why not pass in $db to your functions instead of making it global? To me, the whole point of a function is that it’s reusable code that doesn’t rely on anything other than what is passed in to it.

But back to your question, on the face of it there’s nothing wrong with the code you posted, which means the issue must lie elsewhere.

2 Likes