Forgot Password Recovery (Reset) using PHP and MySQL

Download

Today i will explain how to reset your account password using PHPMailer, PHP and MySQL, in this tutorial i will implement Forgot Password Recovery (Reset) using PHP and MySQL. Before moving towards the reset your password first we need a user registration and login script in php, so if you do not know how to register user and login, you can check out my tutorial about Simple User Registration & Login Script in PHP and MySQL.

To implement forgot password recovery, i will suggest you all to download and set up user registration script so that you can add forgot password functionality in it. However, it is not mandatory if you are an advance user and you can integrate it in your project then you do not need to set it up.

In my user registration tutorial there is a table name users, we will use the same table to check is user exist or not. You will add files of this tutorial in user registration and login script folder.

We will send an email using PHPMailer, if you do not know how to user PHPMailer so you can check my PHPMailer tutorial, i have wrote a detailed tutorial about how to send email in PHP using PHPMailer.

Steps to Forgot Password Recovery (Reset) using PHP and MySQL

We have to follow these steps to implement forgot password functionality.

  1. Create a Temporary Token Table
  2. Create a Database Connection
  3. Create an Index File (Send Email)
  4. Create a Reset Password File
  5. Create a CSS File

Let me give you a quick review of it, first we will create a table to store a token valid for one day for any user. We will also create a form that will take input of email, then we will check either email exist or not, if email is found a temporary token will be generated and email will be sent to the user with the generated token.

Once user clicked on the email token link within one day, user can reset new password. For that purpose we will also create another form that will take input of new password and update it in user table and we will also remove the temporary token from temporary token table once user successfully updated password.

1. Create a Temporary Token Table

We need to create temporary token table, run the following query.

I have also attached sql file of this table in the download file of this tutorial.

2. Create a Database Connection

Create a database connection file with name db.php and add the following script in it, don’t forget to change your database credentials in this file.

We have also define the date timezone, you can set it as per your location. This helps to store data in the timezone of your location.

3. Create an Index File (Send Email)

Now create an index.php file that will take email input and send an email to the user if user is found in the users table.  users table is available in the login and registration script, we are using the same table.

Add the following script in index.php file.

This file is simply checking if email is available in database then generate a random token, save that token in temporary table and send an email to the user with link. Once user click on the link user will be able to set new password.

Please note that i have been using https://www.allphptricks.com/forgot-password/ directory URL in the above script, it should be replace with your project URL where you will upload files of this tutorial.

4. Create a Reset Password File

Now create a rest password file, this will check that is token available in database against the user email and it should be less then one day old, once token expired user will need to regenerate token.

So if token is found user can simply set new password, we will update user password and also delete the token from temporary token table.

Insert the following script in reset-password.php file.

Please note that i have wrote https://www.allphptricks.com/forgot-password/ in these both files, make sure that you also update it as per your web directory URL. You will write your directory where you will set up user registration and login script.

5. Create a CSS File

Create a file with name style.css and keep it in folder css. Paste the following code in it.

Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Facebook Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

68 Comments

  1. sir, please, if you do not mind, may i ask a question???, if yes, all i’ll ask is, do you have an account, weather on facebook, instagram, twitter, or anything, just an account where one can chat with you i n person, i mean one on one?, please, sir, reply my comment with the username, i’ll love to discuss with you on private terms, thanks sir

  2. and dear sir, please, i’m having a problem, please, sir i’m a newbie in the world of php, i’m rather very good at python instead, i’m working on a charity project, and i provided users opportunity to upload a profile photo, along with their informations like username, email, phone number, password, facebook id, etc, and sir i used sessions to send the user a welcome message, immediately he is registered successfully,
    ( FOR EXAMPLE:::
    welcome mary, you have been registered successfully::: )but sir, the problem is i’m able to successfully welcome the new user like in your script too, but how can i also echo the user profile photo? tried but the errors i get is that it keeps on echoing all the photos in the database, and end up filling the page with a lot of user photos, from all the different users, please, sir all i’m begging is, how do i echo every user information, like
    USERNAME,
    EMAIL,
    PHONE NUMBER,
    FACEBOOK ID
    and
    PROFILE PICTURE
    for each user, with sessions, without letting one user to see the photos of another user?
    thanks sir God bless

    1. Hi Mark, i have shared different tutorials, kindly check out my other tutorials, I hope you will get some help and to view image you must need to display image as we normally display but get the image directory URL from the database.

      1. Sir, I understand that, but what I would have loved is if you could make a tutorial on how to echo image, and user informations, using sessions, if you make this tutorial, you’ll see the difference, you’ll have more followers, because, this is one big problem we newbies in php are facing, and sir, I have a little piece of advice for you, please sir, add a link where your users can invite friends, so that we can invite our friends, your tutorials are great, the world needs to know so much more about your great works, if no one else will invite friends, trust me, sir, I’ll do that, I’m not jealous of anyone’s progress, instead I’ll assist the person to progress even more, and sir, before I forget, just create this tutorial I’m telling you about, and you’ll see what I’m saying, I’ve searched far and wide, and I’ve not found any tutorial like that, sir, just try your best, make us a tutorial on how to
        UPLOAD USER PHOTOS IN REGISTRATION FORM
        and echo it separately, to each user According to the users profile, so that a user can see only his photos, please, sir consider this request once again, thanks sir, and God bless you

    2. Well i try my best to share tutorials as much as possible but due to time limit i am not able to write tutorial as per request for now. But i hope later when i will get some spare time i will surely share it. For now i want to hire me for freelance work you can contact me at [email protected]

  3. hi, in your index.php file, you added an sql statement, which says, select from users, and in all your scripts, we can’t find any sql command, or sql statement saying create table users, or something, please, sir, kindly review this, as it’s yielding errors in the script, thanks, sir for your tutorials, i mean they have been so helpful, once again, thanks sir, please, sir remember to review this

    1. Hi Catalin,

      In my tutorial, user can always set new password, if you have reset your password with the key then you can again reset the password, this time with your desired password, simply enter new password in the input field after email verification.

        1. Catalin you must be missing something, i will suggest you to simply copy paste my tutorial and try to run it. Don’t make any changes in the code, only provide database and email credentials. If it is working then you can make changes in the form.
          I have tested the tutorial code and it is working fine, therefore kindly first simply copy paste my code and try to execute it.

  4. Hi, You’ve done a great job. I’ll certainly digg it and
    recommend to my twitter followers personally.
    I’m confident are going to benefited
    out of this website.

  5. Hi, very awesome article. Please what do i alter here($expFormat = mktime(
    date(“H”), date(“i”), date(“s”), date(“m”) ,date(“d”)+1, date(“Y”)
    );)

    if i want to sent the link to expire in hours, or perhaps minutes?

    Anticipate your quick reply.

      1. As’Salam Alikum bro, i am sajid ali from Kasur Pakistan. Brother can you make a tutorial on php search form with multiple input like gender, religion, age, city, country. also include pagination on search result.

  6. Dear Javed Ur Rehman. Finally I solved my problem. I used “$key = md5(“2418*2″.$email);”.

    Thank you for this great tutorial, and your generosity.

  7. Dear Javed Ur Rehman. Thank you for the previous tutorial “Simple User Registration…”. This one is a little bit more complex.

    In this line : “$key = md5(2418*2+$email);
    I got this error : “Warning: A non-numeric value encountered…”

    Thank you for help.

  8. https://www.allphptricks.com/forgot-password-recovery-reset-using-php-and-mysql/

    Please considering the above tutorial, is there any means you can provide table valuables because something seems missing or not added in your tutorial.
    THIS HAS INCLUDES IN THE tutorial index.php

    }else{
    $sel_query = “SELECT * FROM users WHERE email='”.$email.”‘”;
    $results = mysqli_query($con,$sel_query);
    $row = mysqli_num_rows($results);
    if ($row==””){
    $error .= “No user is registered with this email address!”;
    }
    }
    if($error!=””){
    echo “”.$error.”
    Go Back“;
    }else{
    $expFormat = mktime(date(“H”), date(“i”), date(“s”), date(“m”) , date(“d”)+1, date(“Y”));
    $expDate = date(“Y-m-d H:i:s”,$expFormat);
    $key = md5(2418*2+$email);
    $addKey = substr(md5(uniqid(rand(),1)),3,10);
    $key = $key . $addKey;
    // Insert Temp Table
    mysqli_query($con,
    “INSERT INTO password_reset_temp (email, key, expDate)
    VALUES (‘”.$email.”‘, ‘”.$key.”‘, ‘”.$expDate.”‘);”);

    THIS CLEARLY INDICATE THERE SHOULD BE a table users and table password_reset_temp kindly provide there valuable and thanks in anticipation.

    Regards,
    Pucs

  9. Hi, thanks a lot for the resources you provide. the Forgot Password Recovery (Reset) using PHP and MySQL works 100% when importing the SQL files you provided for download but now since I created my own database using the exact field name as your database files, the new password doesn’t update on the database.

    could I be missing something on the database that needs a bit of tweaking

  10. Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\PHPProjectTest\Admin\ForgotPassword.php on line 142

    How to solve it sir??

    1. Hi Harry, download my tutorial from the download option, i can not understand error if you are creating files and giving your own name to file so i do not know which file you are working on.

  11. Hello
    I upload it on my server but the reset password file doesn’t work it shows me that it doesn’t upload to my server but I checked it was there what should I do?

    1. You are not able to connect with your SMTP, make sure you are entering the correct credentials such as username, password, and host. Ask your hosting what you should enter in your host for sending email.

    1. Thanks for the share, you need to make sure that you are using the correct credentials. You are getting SMTP error, ask your hosting what is your server name or host. If you are not sure what is your host name, username and password.

  12. Hi i used your Recovery Code, recovery email was sent to my email but the new password does not update in database. My Db connector is ok.

    1. I think first you should try to execute the same query directly in phpmyadmin database, if it is working fine, then run the same query on page. If it is still working then you should check your code, either you are actually running the same query with same values that are required. You will need to debug your issue step by step.

  13. help me i got this errors

    Notice: Undefined variable: error in C:\xampp\htdocs\proj\indexmail.php on line 17
    Mailer Error: SMTP connect() failed.

  14. if($result){
    echo ”
    You are registered successfully.
    Click here to Login“;
    }
    }else{
    ?>
    getting issue in this part when i try to enter details and make registration it shows nothing a blank page opens up, facing problem here…
    I have also check db connection their is no problem but page can not be redirect to index.php

  15. Warning: A non-numeric value encountered in C:\xampp\htdocs\demo\index.php on line 36

    Fatal error: Cannot redeclare PHPMailerAutoload() (previously declared in C:\xampp\htdocs\demo\PHPMailer\PHPMailerAutoload.php:24) in C:\xampp\htdocs\demo\PHPMailer\PHPMailerAutoload.php on line 31

    why this errors please help me out…

  16. Warning: require(class.phpmailer): failed to open stream: No such file or directory in C:\xampp\htdocs\login\index.php on line 64

    Fatal error: require(): Failed opening required ‘class.phpmailer’ (include_path=’C:\xampp\php\PEAR’) in C:\xampp\htdocs\login\index.php on line 64

    i always got error do i need to edit php mailer ?

      1. Hi Sir!

        Your content is really helpful. Kindly write a blog on how we show all user list only with the admin.

  17. Sir as you use require(“PHPMailer/PHPMailerAutoload.php”) in index.php this page code is not write and thats why my code showing error. so how to remove it.pls also mention whats inside in this PHPMailer/PHPMailerAutoload.php php code

    1. Well it is a library that i am using here, if you are getting error, then you can also check my old where where i explained how to send email using PHP, there you can see if you are missing any step of sending email.

  18. Hello ,

    Please provide country state city & tehsil dynamic drop down code in php, when user select last drop down display all table rows form data base.
    I m using your edit insert update code is very useful.

    1. Hi Humble, i do share tutorials here for learning purpose, you can learn from all my tutorials, if you face any difficulty then you can ask me, i will try my best to give response as soon as possible.
      But i will not be able to take any online or offline classes. So i hope you will find my tutorials helpful. Thanks

Leave a Reply

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