Forget password recovery using Ajax, php and mysqli - Mostlikers

23 July, 2015

Forget password recovery using Ajax, php and mysqli

In this tutorial we are going to discuses about How to recover the registered users forget password recovery using php and mysqli. Here i have shared simple hash email recovery function. Let's see deep discussion. 

Forget password recovery using Ajax, php and mysqli

Live demo             Download



Before stating this script you must know about login and signup process. For reference check our below to related tutorials.


Database

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL
  `password` varchar(250) NOT NULL,
  `active_code` varchar(300) NOT NULL
  PRIMARY KEY (`id`)
)

Index.php - Html & Ajax

Make a simple form with on field for email address. After submitting form value check whether that user already register or not. if email id exist create one random number send email and store active_code column that random value.

<form class="form-horizontal"  action="#" id="form_reset_pwd">  
  <label class="col-sm-3 control-label">Email :</label>
  <input type="text" class="form-control required email" name="email" placeholder="Email"/>
  <button type="button" class="forgot_password">Send Email</button>           
</form>

<script type="text/javascript">
$(document).on('click','.forgot_password',function(){
  var url = "reset_password.php";       
  if($('#form_reset_pwd').valid()){ 
    $.ajax({
    type: "POST",
    url: url,
    data: $("#form_reset_pwd").serialize(), // serializes the form's elements.
    success: function(data) {                    
      if(data==1)
      {
        $('#error_result').html('Check your email');
      } 
      else
      {
        $('#error_result').html('Invalid email id. Please check your email id.');
      }
    }
    });
  }
  return false;
});
</script>

Reset_password.php

Make sure your file in online because email version code support in server only local mail it will support.
<?php 
  $db = new mysqli('localhost', 'root', '', 'mostlikers');
  if($_POST['email']!=""):
      $email=mysqli_real_escape_string($db,$_POST['email']);
      $db_check=$db->query("SELECT * FROM `users` WHERE email='$email'");
      $count=mysqli_num_rows($db_check);
      if($count==1) :
         $row=mysqli_fetch_array($db_check);
         $active_code=md5(uniqid(rand(5, 15), true));
         $link = 'http://mostlikers.2my4edge.com/password-reset/change_password.php?
         user_id='.$row['id'].'&key='.$active_code;         
         $fetch=$db->query("UPDATE `users` SET `active_code` = '$active_code' 
         WHERE `email`='$email' ");
         $to="$email"; //change to ur mail address
         $strSubject="Mostlikers | Password Recovery Link";
         $message = '<p>Password Recovery Link : '.$link.'</p>' ;              
         $headers = 'MIME-Version: 1.0'."\r\n";
         $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
         $headers .= "From: info@mostlikers.com";            
         $mail_sent=mail($to, $strSubject, $message, $headers);  
          if($mail_sent) echo 1;
          else echo 0;  
      else :
        echo 0;
      endif;
  else :
      header("Location:index.php");
  endif;
?>

After user getting password reset link page will redirect to the change_password.php. Here we need to check whether that email and activation present in database.

Change_password.php - PHP code

<?php 
$db = new mysqli('localhost', 'root', '', 'mostlikers');
    if($_GET['user_id']!="" && $_GET['key']!=""):
        $user_id=mysqli_real_escape_string($db,$_GET['user_id']);
        $active_code=mysqli_real_escape_string($db,$_GET['key']);
        $fetch=$db->query("SELECT * FROM `users` WHERE id='$user_id'
        AND `active_code` = '$active_code'");
        $count=mysqli_num_rows($fetch);
        if($count!=1) :
          header("Location:index.php");
        endif;
    else :
        header("Location:index.php");
    endif;
?>

Change_password.php - HTML & AJAX

<form method="post" autocomplete="off" id="password_form">
  <label>New Password</label>
  <input type="password" id="passwords" name="password"  class="form-control required">
  <label>Confirm password</label>
  <input type="password" id="cpassword" name="cpassword" equalto="#passwords"
  class=" required" value="">
  <div id="error_result"></div>
  <input type="hidden" name="id" value="<?php echo $user_id; ?>" id="id">
  <button type="submit" id="btn-pwd" class="btn btn-primary">Submit</button>              
</form>

<script type="text/javascript">
$(document).on('click','#btn-pwd',function(){
  var url = "new_password.php";       
  if($('#password_form').valid()){
    $.ajax({
    type: "POST",
    url: url,
    data: $("#password_form").serialize(),
      success: function(data) {                    
        if(data==1)
        {
          $('#error_result').html('Password reset successfully.');
          window.setTimeout(function() {
          window.location.href = 'index.php';
          }, 2500);
        } 
        else
        {
          $('#error_result').html('Password reset failed. Enter again.');              
        }
      }
    });
  }
  return false;
});
</script>

New_password.php

update particular user table password column to the new password and active_code column empty. 
<?php 
$db = new mysqli('localhost', 'root', '', 'mostlikers');
if($_POST['password']!=""):
    $pass_encrypt=md5(mysqli_real_escape_string($db,$_POST['password']));
    $user_id=mysqli_real_escape_string($db,$_POST['id']);
    $fetch=$db->query("UPDATE `users` SET `password` = '$pass_encrypt',
    `active_code`='' WHERE id='$user_id'");
    if($fetch): echo 1;  
    else : echo 0;
    endif;
else :
    header("Location:index.php");
endif;
?>


Thank you for visiting. if have any queries write your comments below.

"You have to learn the rules of the game. And then you have to play better than anyone else. .  "
                                             
                                         - Albert Einstein








Related Topics

9 comments:

  1. I didn't receive any activation code but am able to change the password..

    ReplyDelete
  2. Nice tutorial :)

    Only i wonder, how do i use this when i have it by php 5.5 password hashing on database?

    ReplyDelete
    Replies
    1. Thanks for your comment. I will post about php 5 password hash function currently follow the refernce code


      $pass_encrypt = password_hash($_POST['password'], PASSWORD_BCRYPT);
      // Insert $pass_encrypt into database against user

      Login page code
      // Fetch hash+salt from database, place in $pass_encrypt variable
      // and then to verify $_POST['password']:
      if (password_verify($_POST['password'], $pass_encrypt)) {
      // Verified
      }

      Delete
  3. I wanted to say, it is saver to make an connection to a database from a different file.
    Also because, you use php as file extension anyways.

    So you could call the database connection file with: include 'filename';


    Greets Tightis

    ReplyDelete
  4. This really helped me, but I'm having problem in change_password.php , after I click the link that was sent to my email, it will direct me to change_password.php right? And it will allow me now to set my new password, but I tried and when I click "submit", it just reloads the page, no error. Can u explain how did it happen and what might be the wrong is?

    ReplyDelete
    Replies
    1. Hi Louie,

      I have checked live demo it's working fine. Share your verification link. change_password.php page code

      Delete
  5. great tutorial - thank you ! Would it be worth deleting the active code from the users record in the database so that the email reset link wont work again until the user requests a new password reset link?

    ReplyDelete