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..
Previous Post
Next Post

post written by:

45 comments:

  1. Hello to all, how is the whole thing, I think every one is
    getting more from this web page, and your views are nice designed for new
    viewers.

    ReplyDelete
  2. Yes! Finally something about Hooda Math.

    ReplyDelete
  3. With havin so much content and articles do you ever run into any problems of plagorism or copyright violation?
    My site has a lot of unique content I've either created myself
    or outsourced but it appears a lot of it is popping it up all over the internet
    without my agreement. Do you know any solutions to help stop content from being ripped off?

    I'd genuinely appreciate it.

    ReplyDelete
  4. I every time used to study piece of writing in news papers but now as I am a user of web so from now
    I am using net for content, thanks to web.

    ReplyDelete
  5. Wow, fantastic blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your website
    is fantastic, let alone the content!

    ReplyDelete
  6. Howdy, i read your blog from time to time and i own a similar one
    and i was just wondering if you get a lot of spam comments?
    If so how do you reduce it, any plugin or anything you can recommend?
    I get so much lately it's driving me mad so any support is very much appreciated.

    ReplyDelete
  7. Hi I am so thrilled I found your webpage, I really found you by error, while I was researching
    on Digg for something else, Anyways I am
    here now and would just like to say many thanks for a remarkable post and a all round enjoyable blog (I
    also love the theme/design), I don't have time to go through it
    all at the moment but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the excellent work.

    ReplyDelete
  8. Heya i'm for the primary time here. I found this board and I find It really helpful & it helped me out a lot.
    I hope to provide one thing again and help others like you aided
    me.

    ReplyDelete
  9. Hello There. I found your blog using msn. This is a really smartly written article.
    I will make sure to bookmark it and come back to learn extra of your helpful information. Thanks
    for the post. I will definitely return.

    ReplyDelete
  10. Excellent blog here! Also your website quite a bit up very fast!

    What web host are you using? Can I get your affiliate link on your host?
    I want my web site loaded up as fast as yours lol

    ReplyDelete
  11. I feel this is one of the such a lot vital information for me.

    And i'm happy studying your article. However should statement on few common issues, The site style is great, the articles is
    truly excellent : D. Excellent process, cheers

    ReplyDelete
  12. Good article. I definitely love this site. Continue the good work!

    ReplyDelete
  13. It's awesome to visit this site and reading the views of all mates regarding this piece of writing, while I am also zealous of getting knowledge.

    ReplyDelete
  14. Hello there, I do believe your site may be having browser compatibility problems.
    Whenever I take a look at your web site in Safari, it looks
    fine but when opening in Internet Explorer, it's got some overlapping issues.
    I merely wanted to give you a quick heads up! Besides that, fantastic website!

    ReplyDelete
  15. You actually make it appear so easy with your presentation however I
    in finding this matter to be really one thing that I believe I would by no means
    understand. It kind of feels too complicated and very broad for me.

    I am taking a look forward to your next post, I will
    try to get the hang of it!

    ReplyDelete
  16. Hi, i think that i saw you visited my web site thus i came to “return the favor”.I am
    attempting to find things to improve my site!I suppose its ok to use some of your
    ideas!!

    ReplyDelete
  17. Hi there to all, how is everything, I think every one is getting more from this site, and
    your views are pleasant in favor of new visitors.

    ReplyDelete
  18. Hi there I am so glad I found your blog, I really
    found you by error, while I was searching on Google for something
    else, Regardless I am here now and would just like to say cheers for a remarkable post and a
    all round thrilling blog (I also love the theme/design), I don't have
    time to look over it all at the minute but I have bookmarked it
    and also included your RSS feeds, so when I have time I will be back to
    read more, Please do keep up the excellent job.

    ReplyDelete
  19. Great weblog right here! Additionally your website loads up fast!

    What host are you the use of? Can I get your affiliate hyperlink to your host?
    I want my website loaded up as quickly as yours lol

    ReplyDelete
  20. hey there and thank you for your information – I have certainly picked up
    something new from right here. I did however expertise some technical issues using this web site, as I experienced to reload the site lots of times previous to I could get it
    to load properly. I had been wondering if your web host is
    OK? Not that I am complaining, but slow loading instances
    times will very frequently affect your placement in google and can damage your quality score if ads and marketing with Adwords.
    Well I'm adding this RSS to my e-mail and can look out for a lot more of your respective interesting
    content. Ensure that you update this again very soon.

    ReplyDelete
  21. I'm gone to tell my little brother, that
    he should also go to see this webpage on regular basis to get updated from most recent
    reports.

    ReplyDelete
  22. Hello there! I could have sworn I've been to this site
    before but after checking through some of the post I realized
    it's new to me. Anyhow, I'm definitely happy I found it and I'll be bookmarking and checking back frequently!

    ReplyDelete
  23. Hello, i think that i saw you visited my site thus i came
    to “return the favor”.I'm trying to find things to
    enhance my website!I suppose its ok to use a few of your ideas!!

    ReplyDelete
  24. I all the time used to study post in news papers but now as I am a user of web
    thus from now I am using net for content, thanks to web.

    ReplyDelete
  25. Appreciate this post. Will try it out.

    ReplyDelete
  26. After I originally left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and from now on every
    time a comment is added I receive 4 emails with
    the same comment. Perhaps there is a way you can remove me from that
    service? Thank you!

    ReplyDelete
  27. First of all I want to say terrific blog! I had a quick question that I'd like to ask if you
    don't mind. I was curious to know how you center yourself and clear
    your head prior to writing. I've had difficulty clearing my thoughts in getting my thoughts out there.
    I truly do take pleasure in writing however it just seems like the first 10 to 15 minutes are usually wasted simply just trying to
    figure out how to begin. Any ideas or tips? Kudos!

    ReplyDelete
  28. Hi there! I simply want to offer you a big thumbs up for the
    great information you have right here on this post. I will be coming back to your web site for
    more soon.

    ReplyDelete
  29. This information is worth everyone's attention. When can I
    find out more?

    ReplyDelete
  30. Hi! This post could not be written any better! Reading this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this article to him.
    Pretty sure he will have a good read. Many thanks for
    sharing!

    ReplyDelete
  31. Thanks for sharing your thoughts about Abcya 100. Regards

    ReplyDelete
  32. Does your website have a contact page? I'm having trouble locating it but, I'd like to shoot you an email.

    I've got some suggestions for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it grow over time.

    ReplyDelete
  33. I'll right away clutch your rss as I can not find your email
    subscription hyperlink or e-newsletter service. Do you've any?

    Please allow me know in order that I may subscribe.
    Thanks.

    ReplyDelete
  34. When someone writes an paragraph he/she keeps the
    idea of a user in his/her brain that how a user can know
    it. So that's why this piece of writing is great. Thanks!

    ReplyDelete
  35. Woah! I'm really digging the template/theme of this blog.
    It's simple, yet effective. A lot of times it's hard to get that
    "perfect balance" between user friendliness and appearance.
    I must say you have done a fantastic job with this.
    Also, the blog loads very quick for me on Internet explorer.

    Superb Blog!

    ReplyDelete
  36. Superb website you have here but I was curious about if you knew
    of any forums that cover the same topics discussed here? I'd really like
    to be a part of community where I can get responses from other knowledgeable individuals that share the same interest.

    If you have any recommendations, please let me know.
    Bless you!

    ReplyDelete
  37. I was suggested this blog by my cousin. I'm not sure whether this post is written by
    him as no one else know such detailed about my problem.
    You're wonderful! Thanks!

    ReplyDelete
  38. For newest news you have to go to see the web and on world-wide-web I found this web site as a best web page
    for hottest updates.

    ReplyDelete
  39. Hi! I've been following your blog for a while now and finally got the bravery to go
    ahead and give you a shout out from Austin Tx!
    Just wanted to mention keep up the excellent work!

    ReplyDelete
  40. Exceptional post but I was wanting to know if you could write a litte more on this topic?
    I'd be very grateful if you could elaborate a little bit more.
    Cheers!

    ReplyDelete
  41. I am not sure where you're getting your info, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for excellent information I was looking for this information for my mission.

    ReplyDelete

Hit me with a comment!