forgot password php

How to create a Forgot Password PHP

Today we will learn how to create a forgot password PHP page. If the user is getting troubles sign in your account, we can send a recovery email to reset and set a new password. After we have created a Login Form, Registration Form in PHP and send a confirmation email to new users confirm their account. Now we need create a password recovery page.

 

How the user recover password?

If user have forgotten his password, he can:

  • access to recovery password page;
  • enter is email to receive a recovery email with:
    • a link to click and set a new password.
  • when the user click on the link he is redirected to the reset password page;
  • after we reset his password he receive a new email saying that his password has changed.

 

First we will create the ‘ recovery_page.php ‘ file, where the user can insert his email to receive the recovery email.

<?php include('connection.php') ?>
<!DOCTYPE html>
<html>
      <head>
        <title>W7code - Recover Password</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link rel="stylesheet" type="text/css" href="style.css">
        <meta name=viewport content="width=device-width, initial-scale=1">
      </head>
      <body>
          <div class="content">
            <a class="rzbox_logo" href="user_panel.php">
              <img src="https://www.w7code.com/wp-content/uploads/2017/11/cropped-w7code_logo.png" />
            </a>
              <form method="post" action="">
                <div class="input_data">
                	<input type="email" name="forgot_password" placeholder="Insert Email"/>
                </div>
                <div class="input_data">
                  <button type="submit" class="button button1" name="submit_forgot_password">Recover Password</button>
                </div>
              </form>
          </div>
      </body>
</html>

 

 

Now we need create a new table in our database named ‘ recovery_password ‘. Which will contain the request for a new password. This table will store the username, email, hash ( which is randomly generated) and password_active ( this last is to restrict, the password change only 1 time using the link).

CREATE TABLE `recovery_password` (
  `username` varchar(40) NOT NULL,
  `hash` varchar(32) NOT NULL,
  `email` varchar(50) NOT NULL,
  `active` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

Now we have collected the email, we need to process this information. For this we will add some code to our ‘ connection.php ‘ file which we have create in the previous class. This code will be responsible to send the email with the recovery link:

//if user isset 'submit_forgot_password' button
//and the field 'forgot_pasword' is not empty run the code
if(isset($_POST['submit_forgot_password']) && !empty($_POST['forgot_password'])){

  //this line collect the user email and escape it
  echo $emailAccount = mysqli_real_escape_string($db, $_POST['forgot_password']);

  //we are checking in our database if is any account with the user email
  // equal to the user have inputed
  $recoverConnect = "SELECT username, email, active_account FROM user WHERE email='$emailAccount' AND active_account='1'";
  $recoverResult = mysqli_query($db, $recoverConnect);

  //if exist an account in the database with that features run the code
  if(mysqli_num_rows($recoverResult) >0){
    //we create a random hash to recover the password
    $hashRecover = md5(rand(0,1000));
    //we are getting the data individually from database
    $row = mysqli_fetch_assoc($recoverResult);

    //we are setting username and email
    $username = $row['username'];
    $email = $row['email'];

    //we are insert into 'recovery_password' table the information
    //that we need to the user change the password
    $query = "INSERT INTO recovery_password (hash, username, email) VALUES('$hashRecover', '$username', '$email')";
    mysqli_query($db, $query);

    //set this to your website url
    $websiteUrl = "http://www.w7code.com";
    //set this to your email that you want
    $from = "noreply@w7code.com";
    //set the email for the user need to reply
    $replyTo = "email@w7code.com";
    //this is the email that we have to send the recovery email
    $to      = $email;
    $subject = 'Reset Password';
    $message = '
    Hello,
    Here you have the link to reset password:
    '.$websiteUrl.'/change_password.php?username='.$email.'&hash='.$hashRecover.'

    ';
    $headers = 'From: '.$from. "\r\n" .
        'Reply-To: '.$replyTo. "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

  }else{
    echo 'The password already have been changed';
  }
}

 

Now that we have created the system of sending the recovery email, we need create the ‘ change_password.php ‘ file where you can change your password.

<?php
  session_start();
  include('connection.php');
?>
<!DOCTYPE html>
<html>
      <head>
        <title>W7code - Set New Passord</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <meta name=viewport content="width=device-width, initial-scale=1">
      </head>
      <body>
        <div class="content">
          <a class="rzbox_logo" href="admin_panel.php">
            <img src="https://www.w7code.com/wp-content/uploads/2017/11/cropped-w7code_logo.png" />
          </a>
          <br>
            <?php
              //we get and escape the email from url using :
              $email = mysqli_real_escape_string($db, $_GET['username']);
              //we get and escape the hash from url using :
              $hash = mysqli_real_escape_string($db, $_GET['hash']);

              //using this query we select from 'recovery_password' table the data from the user
              //we compare the values to the values that user inputed
              //to check if password already have been changed or to check if the request exist
              $query = "SELECT email, hash, active FROM recovery_password WHERE email='$email' AND hash='$hash' AND active='0'";
        			$results = mysqli_query($db, $query);

              //we are getting the rows where the data is equal to the $query
              $match = mysqli_num_rows($results);
            // if the rows number is equal to 1 it means, that have a password recovery request
            //and still is active
            if($match == 1){
              //if is active we show the fields to change the password
              ?>
                  <form method="post" action="">
                    <div class="input_data">
                      <input type="password" name="password1" placeholder="New Password" />
                    </div>
                    <div class="input_data">
                      <input type="password" name="password2" placeholder="Confirm New Password" />
                    </div>
                    <div class="input_data">
                      <button type="submit" class="button button1" name="submit_new_password">Change Password</button>
                    </div>
                  </form>
              <?php
              //we are get and escape the "New Password"
              $newPassword1 = mysqli_real_escape_string($db, $_POST['password1']);
              //we are get and escape the "Confirm New Password"
              $newPassword2 = mysqli_real_escape_string($db, $_POST['password2']);

              //if password doesn't macth echo "The two passwords do not match"
              if ($newPassword1 != $newPassword2) {
                echo "The two passwords do not match\n";
              }else{

              //if thw two password matchs encrypt it to then we store in the database
              $password = md5($newPassword1);

              //here we are uptade the user new password
              $queryPassword = "UPDATE user SET password='$password' WHERE email='$email'";
              mysqli_query($db, $queryPassword);

              //if user press the button "Change Password" and the twho passowd matchs
              if(isset($_POST['submit_new_password']) && $newPassword1 == $newPassword2){
                //we update the status of recovery request to actvive
                //which means that we can not change the password using that link
                $query = "UPDATE recovery_password SET active='1' WHERE email='$email' AND hash='$hash'";
                mysqli_query($db, $query);
                //echo 'Your password has been changed'
                echo 'Your password has been changed';
              }
            }

            }else{
              //if user already have changed password using that link
              //the message will be printed is:
              echo 'Your password already has been changed';
            }
             ?>
          </div>
      </body>
</html>

 

Learn to:

Download the Full Project here.

Final Result:

forgot password php forgot password php send email

Have any doubt?Please comment it bellow, we will solve it!

 


Leave a Reply

Your email address will not be published. Required fields are marked *