1. Code
  2. PHP

Creating an Advanced Password Recovery Utility

Scroll to top
Read Time: 25 min

In my last tutorial, 'A Better Login System', a few people commented on how they would like to see a tutorial on password recovery, which is something you don't always see in user access tutorials. The tutorial I am bringing you today will deal with just that. Using mySQLi, we will learn to recover unencrypted and (one-way) encrypted passwords.


Password recovery is always a useful feature to have on your site; however, many tutorials dealing with user authentication neglect this topic. In this tutorial, I will cover handling encrypted and unencrypted passwords, basic mySQLi functions, and we will also build in a temporary lockout if the user answers the security question incorrectly too many times. I hope that by the end of this tutorial, you will have a better understanding of recovering passwords, and the mySQLi interface.

For unencrypted passwords, we will create an email that will email the password to the user's registered email address.

When dealing with encrypted passwords, things are a little more complicated. When a password is encrypted with md5(), it can't be decrypted. Because of this, we will send the user an email with a link that will allow them to reset their password. To secure this process we will use a unique email key that will be checked when the user returns to the password page. Our passwords will be encrypted with a salt to improve security.

IMPORTANT NOTE: This tutorial uses the mysqli interface instead of mysql. Although the PHP documentation says that it should work, I was unable to use the mysqli classes successfully until I upgraded from 5.1.4 to 5.2.9. If you are getting errors about using an 'unsupported buffer', try the upgrade. You may also have to change your php.ini file to load the mysqli extension if you see errors about not finding the class mysqli.

Depending on whether your site uses encrypted or unencrypted user passwords, you should follow the directions a little differently. The directions as a whole are for encrypted passwords; but there are special notes here and there for dealing with the regular passwords.

Step 1: Database Tables

After creating a new database, we need to create three tables:

Database tablesDatabase tablesDatabase tables

The recoveryemails_enc table holds information about the emails that are sent out to allow users to reset passwords (such as the security key, the userID and expiration date). The users tables holds the user information. If you are following the encrypted example, use the users_enc table, otherwise use the table users.

If you already have a table of users, you will need to add security question and answer fields. The question field will hold an integer which equates to a security question in an array, and the answer field holds a varchar answer. The security question is used as verification before sending a password email. Here is the code you should run to create the tables (also available in sql.txt in the download):

Step 2: Database Include

Database ConnectionDatabase ConnectionDatabase Connection

We need to create an include file so that we can connect to our database. For our database interaction, we will use mysqli, which provides an object-oriented approach to database interaction. Create a file called assets/php/database.php. We will add the following code to it (replace the variable values with the information appropriate for your hosting situation):

In the first line of the code, we call session_start(), we will not actually use the session variables but you will need a session as part of a user login system. Then, we call ob_start() to start the output buffer.

Lines 4-8 set up our variables to connect to the server. Then we create a new mysqli object by passing it our variables. For the remainder of our script, $mySQL will allow us to interact with the database as needed.

Mysqli handles error events slightly different, so we have to check the connect_error property after connecting, and print an error message if something went wrong. This goes the same for making queries; we must check the error property of our query or connection object to check for errors.

Step 3: Create the Forgot Password Page

Let's start off this step by creating the file forgotPass.php. Then, we'll add this code to it:

This html gives us a nice base to build on and gives us this:

Page TamplatePage TamplatePage Tamplate

Then, add this code to the very top of the page, above the html we just entered:

The first things we do are include the database file and a functions file that we will create shortly. Then we create a variable called $show that determines which interface element to display, by default we want to show the email input form.

After that, we check some session variables. If the session lockout variable is true, and more than 900 seconds (15 min) have elapsed since the lockout took place, we want to end the lockout, which lines 7 and 8 do for us.

Then we create an if block that checks to see if anything has been posted to the page. You can also see that we are checking to make sure that $_GET['a'] is not set, this variable will be set when the user clicks on the link in their recovery email, so if that is happening, we can skip the post check. Also in the logic block, we make sure that the lockout variable isn't set to true.

Once inside the if block, we use switch($_POST['subStep']) to check which stage of the form has been submitted. There are three stages that we will handle: Step 1 means that we just entered a username or email address that we want to reset the password for. To do that, we call the function checkUNEmail(), which we will write momentarily. This function returns an array that has a boolean value to determine if the user was found, and an integer of the userID if the user was found. Line 17 checks to see if the user check returned false (the user wasn't found), if so we set the error flag, and the $show variable so that we see the 'User Not Found' message. If the user was found, we should show the security question form, and set $securityUser so we know which user to load the question for.

In stage 2, we have submitted the security question. The first thing we do here is check to make sure that both a userID and an answer were returned. If either one was omitted, we display the security question form again. If both values were included, we call a function to check the answer against the database. This function returns a simple boolean. If the question was answered correctly, we will show the success page, send the reset email, and set the bad entry count to 0. If the question was answered incorrectly, we display the question page again, and also increment the bad answer counter.

The third stage happens after the user has received the password reset email, and has clicked on the link and submitted the password reset form. First, either userID or the security key are empty, we redirect to the homepage. Then we check to make sure that the two passwords match and were not empty. If they don't match, we show the password reset form again. If they do match, though, we show the success message, and call a function to reset the user's password.

NOTE: If you are using unencrypted passwords, you can leave out case 3 above. This is the method that saves a new password after it has been reset. Since we can email unencrypted passwords, they don't need to reset it.

Now we will add an else block to that same if block from above:

This else block determines if $_GET['a'] is set, which means that the user has come to the page via the email reset link. If we've figured out they clicked on the link, we want to check if they email key is valid using checkEmailKey(). If the key is not found or not valid, it returns boolean false, and we display the invalid key message. If the key is valid, however, it returns an array that we can grab the userID out of (so we know which user's password to reset).

NOTE: If you are using unencrypted passwords, you can leave out the elseif block. This deals with displaying the password change form after clicking on the link in the email.

The second if block there checks to see if the user has answered the security question incorrectly more than 3 times. If they have, we set the lockout variable to true, and set the lockout time, which is the time the lockout went into effect. Notice that if the lockout time is already set, we will use that variable, but if not, we will generate a new time.

Setting a speedlimit is important for security. Mostly it will serve to deter people from just sitting there and trying to guess the answer to security questions. It can also help to prevent bots from submitting the form over and over. The main drawback of this method is that a user can just delete the PHPSESS_ID cookie, and then they can start over. If you want a very secure solution, you could add a 'lockout' flag to the users table, and when they have answered wrong 3 times, set that flag to true. Then you can write some code to lockout if they try to access the account.

Step 4: Function file


Now let's create the file assets/php/functions.php to hold all of the functions we were referencing earlier. Now let's go through them a few at a time:

NOTE: In the sample files, the encrypted example uses the table 'users_enc', while the unencrypted example uses the table 'users' so the table name will change in your functions depending on which version you use.

At the top of the file, we want to define PW_SALT, which is the salt we will use to encrypt passwords throughout. The first function takes the username and password values from the $_POST and sees if a matching user exists in the database. The first thing we need to do is make $mySQL global so we can access the database. We also create a generic error array that we will return if no user was found. Then we check to see if there is a value for the email. If there was, we build a mySQLi prepared statement. The great thing about using prepared statements is the security, especially when dealing with user input, the overall process is similar to using sprintf().

Notice that we call the ->prepare() method with our SQL query as the parameter, and use question marks where our variables would go. Also note that we don't put any form of quotes around the question marks (even for string).This is what allows us to parameterize a statement. mySQLi::prepare() will return true if the statement was created successfully. If it was created, we need to bind parameters to our query using mySQLi::bind_param(). This function accepts at least two arguments. The first is a string of letters that represent the datatypes of the data to be bound. The rest of the arguments are the variables that you want to be in each parameter. In our case, we are using 's' (for a string), and $email, since that variable has the email address. Note that the order is important, so the first question mark in your query corresponds to the first letter in the format string, and the first variable.

Then we need to call ->execute() and ->store_result(). These two methods run the prepared query and store it in memory until freed. Then we check for the number of rows returned to make sure that the user was found. ->bind_result() is very similar to ->bind_param() except in the opposite direction. It allows us to take a returned value from a result, and map it to a local variable. Variables are assigned based on their order in the result set. The local variable is not actually written until we call ->fetch(), after we call ->fetch(), the variable $userID will hold the variable from the database. Then we use ->close() on the query to free the result. Lastly, we will return an array that holds the boolean value for success and an integer for the userID.

getSecurityQuestion() accepts the id of a user, and returns their security question as a string. Once again, we make $mySQL global. Then we create an array of the 6 different security questions possible. Using a method similar to the above, we see which security question the user has selected, then we return that index from the array.

checkSecAnswer() accepts a userID and a string answer and checks the database to see if it is correct. Note that we are converting the passed answer and the database answer to lowercase to increase chances of a match (optional for you). This is an excellent example of a multi parameter prepared statement. Notice the order of the arguments in the bind_param() method. This function will return true if it finds a record where the userID and the answer match what is passed. It will return false otherwise.

This function takes care of sending the email to reset a password. We start out by making a SQL query to get the username and email address of the passed user. After binding the parameters and the result, we close the query. For security reasons, we only want the link we generate to be good for 3 days. To do this, we create a new date that is 3 days in the future. Them, using several of the values that are passed in, the date, a random number and our salt, we generate an MD5 hash that will be our security key. Because of the every changing future date and random number, we should be assured a completely random key every time. Then we build a SQL query to insert it into the database. After executing the query, we make the link that will be sent in the email. We want to include 'a=recover' and our key, and userID which we base64_encode() and urlencode() to make it not readable. Once the link is generated, we make the rest of our email text and send it.

NOTE: If you are using the unencrypted example, you want to change your message text to instead print out the variable $pword instead of a link to reset the password.

NOTE: If you are developing this on a local server, it is unlikely that you have smtp installed, so you will be unable to send mail. This is why we are using the @mail() command (to prevent error messages). Also for that reason, this function returns the string of the message so it can be printed on the screen. Now for the last 3 function:

The first function checks the email key that was passed. We make a date string to represent today's date (so we know if the key is expired). Then our SQL checks to see if any records exist for a key that matches the passed user, security key, and that the expiration date is after right now. If such a key exists, we return an array with the userID in it, or false otherwise.

The function updateUserPassword() takes care of changing the actual password in the database. First we verify the email key against the passed in user and key info to make sure things are safe. We generate a new password by combining the passed password and the previously defined salt, and then running md5() on that string. Then we perform our update. Once that is completed, we delete the record of the recovery key from the database so it can't be used again.

NOTE: The function updateUserPassword() is not needed in the unencrypted example, since we are not changing their password.

getUserName() is simply a utility function to get the username of the assed userID. It uses a basic SQL statement like the others.

Step 5: Complete the Forgot Password Page

Now that we have the functions we need built, we'll add some more to forgotPass.php. Add this code inside the div with the id "page":

This code will deal with actually displaying all of the interface elements. We start off by examining the $show variable from earlier with switch(). As you may remember from earlier, there are many different values that $show can have, so we must create a case for each one. The first case, "emailForm", is where the user will enter either a username or email that they want to recover the password for. Basically we need two text fields, and a hidden input so we know which step we have submitted. There is also an if ($error == true) block that will display an error message if the $error flag is true.

Email FormEmail FormEmail Form

The second case is "securityForm". This is where the security question will be displayed. You can see that we also have an error message, and we use getSecurityQuestion() to print the security question. Then we have an input for the answer, as well as the step, and the userID.

Security QuestionSecurity QuestionSecurity Question

The message for "userNotFound" is simply a text message that tells the user that the record wasn't found.

"SuccessPage" is shown when the security question has been answered correctly and the email has been sent. Notice that we have printed out the email message at the bottom of this prompt, you would not do this in a production environment, because then you give the person instant access to the security code meant only for the registered user.


Let's continue with this code:

Continuing the switch statement, we have "recoverForm", which displays the form to change the password. We print out the user's name, and an error message if needed. Then we have input fields for a password and confirmation password, the submission step, the userID and the security key from the email. For the key and userID, e are using the special if() syntax to make sure that we are getting the variable from the right place. If the querystring variable is null, we will look in the post variables to make sure that we always have a value here.

Change PasswordChange PasswordChange Password

Then, "invalidKey" means that the key provided did not exist or was expired. The "speedLimit" message is displayed if the user has been locked out because of too many incorrect answers. Finally, we call ob_flush() to send the page to the browser, and $mySQL->close() to disconnect from the database.

NOTE: "recoverForm" and "invalidKey" messages from above are not needed for unencrypted passwords.


In this article, we've looked at adding an extremely useful feature for any membership site. Whether you store your passwords as plain text or encrypted, this tutorial should have helped you add a password recovery function. We looked at the logic behind encrypting passwords, sending emails to recover the passwords, and some security concerns when doing so.

Additionally, we looked at using mysqli to improve our interaction with the database. While this tutorial didn't go that in depth with mysqli, it should leave you a little better off than you were before.

I hope you can use the techniques discussed here to add this extremely useful feature to your next user membership site.

Note on the Download: In the download files, I have implemented both encrypted and unencrypted versions in two different folders.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.