Friday, 6 January 2017

How to create forgot password system in PHP

Hi, I am trying to make forgot password script on www.thewallclone.com and I do not worry about it, because it was successful. In this post we are going to learn how to implement forgot password system on our web application, recover lost password from account using php, on this forgot password system we have form for account verification that will help us to create a new password for that account.




First, we are to verify either the user email address to send reset link for an opportunity to create new [fresh] password. The Password recover email has a link to the page where we can reset password.

How does password recovery work ?

Password Recovery help you recover lost and forgotten password or an opportunity to create new password or reset password.
E-mail verification is use to send a reset link to the user. Generate a unique random code, tie it to the user account, probably set an expiration time this is optional and store them into the database. Then generate a unique link and mail it to the user email address during registration.
So, for the verification aspect. When the user clicks the link, they will have the following data at your disposal: the email, and the token (a unique random code). That should be enough to do verification.  This part do the following checks:
  • Is the email valid?
  • Is the email-token binding valid?
  • Is the token expired? (Optional)
  • Has the token been used?
  • Is the token field empty?

If all checks out, allow the user to provide a new password/verify their email. No matter success or failure, it is very important to invalidate the token after use.
Check demo here download source code.

Basic PHP mail() Function code to send emails from a form


Now, on this tutorial we are using basic PHP mail() Function code to send emails from a form. You can use the PHP mail() function to send an email with PHP. The simplest way to do this is to send a text email. This is one way to handle sending emails to your users.


/* Send a link to reset password */
$to = $email;
$subject = "reset password link";
$header = "By codexpress";
$body = "here is your link to reset your password
For active your account, visit the link below to complete : 
http://www.thewallclone.com/updatepassword.php?email=$email&code=$code";

$sent=mail($to,$subject,$body,$header);
if ($sent) 
{
echo ' Sent success';
} 

index.php

Index contain verification form and validation code change where you find thewallclone.com to your own domain.

Html form

<?php
include 'config.php';
?>
<!DOCTYPE HTML>
<html>
<head>
    <title>How to create forget password recovery procedure in PHP by Codepress</title>
</head>
<body>
 <h2>Reset Password</h2>
    <form method="post" action="#">
    
        <p><label>Email: </label><input type="text" name="email" /></p>
        <p><input type="submit" name="submit" value="Reset"/></p>
    </form>
</body>
</html>

Verification code

<?php
 if (isset($_POST['email']) && ($_POST['email']!="")) {
  # code...
  $email=trim($_POST['email']); // get email address from user form
  $code=md5(uniqid(true)); // random alphernumeric character store in $code variable
  
  if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

   $checkmail=$db->query("SELECT email FROM users WHERE email='$email' ") or die(mysqli_error('Run time error...'));
   $count=mysqli_num_rows($checkmail); // check if user is on our data base

   if ($count==1) { // if email is stored in our database update lost password field with random code for reset
    # code...s
    $inserted=$db->query("UPDATE users SET lost='$code' WHERE email='$email' ");
      // update our table users with unique random code
      /* Send a link to reset password */
      $to = $email;
      $subject = "reset password link";
      $header = "By codexpress";
      $body = "here is your link to reset your password
      For active your account, visit the link below to complete : 
      http://www.thewallclone.com/updatepassword.php?email=$email&code=$code";

      $sent=mail($to,$subject,$body,$header);
      
       # code...
    if ($inserted) { /* update is successfull */
     # code...
     echo("Check your mail we have sent you reset link to change your password! <br>");

    }
   }
   else
   {
     echo("Oops! Sorry, $email dose not belong to any account!");
   }

  } else {
    echo("$email is not a valid email address");
  }
 }
 $db->close();
 ?>

updatepassword.php

This file contain form reset password after done all the verification and validations

<?php
include 'config.php';
?>
<!DOCTYPE HTML>
<html>
<head>
    <title>How to create forget password recovery procedure in PHP by Codepress</title>
</head>
<body>
<?php
 if (isset($_GET['email']) && ($_GET['code']!="")) {
  # code...
  $code=$_GET['code'];
  $email=$_GET['email'];

  $checkmail=$db->query("SELECT email FROM users WHERE email='$email' AND lost='$code' AND lost!='' ") 
  or die(mysqli_error('Run time error...'));
  $count=mysqli_num_rows($checkmail);
  if ($count) {
   if (isset($_POST['password']) AND ($_POST['password']!="")){

     $password=md5($_POST['password']);
     $repassword=md5($_POST['repassword']);
     if ($password===$repassword) {
      # code...
      $inserted=$db->query("UPDATE users SET lost='', password='$password' WHERE email='$email' ");
       // insert into our table users with new password
      if ($inserted) {
       # code...
       echo "<h1>Successfully changed!</h1>
       <a href='index.php'>Return home</a>";
      }

     }
     else
     {
      echo "Password do not match!";
     }

   }
   # code...
   echo '
    <h2>Create New Password</h2>
    <form method="post" action="">
          <p><label>New Password: </label><input type="text" name="password" /></p>
          <p><label>Retype New Password: </label><input type="text" name="repassword" /></p>
          <p><input type="submit" name="create" value="Submit"/></p>
      </form>
   ';

  }
  else
  {
   echo "<h2>Error occure! <a href='index.php'>Return</a></h2>";
  }

  
 }
 $db->close();
 ?>
</body>
</html>
 

Database Schema

Here is the database schema for this tutorial.

-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `img` varchar(300) DEFAULT NULL,
  `lost` varchar(1000) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
Don’t forget to share, subscribe to newsletters, or just say hello..

No comments:

Post a Comment

Hit me with a comment!