Forgot Password Recovery (Reset) using PHP and MySQL


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 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 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.


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.


  1. This will result in a non-numeric value found (“+$email”) and I’m not entirely sure why you would use 2 x 2418?

    $key = md5(2418*2+$email);

    Great tutorial though, thank you very much.

  2. Hi,

    Until sending password reset link to the user through mail everything works fine, but when we click on the link to reset password the page is blank. I tried a many ways to echo also nothing is printing. Please help me out in this I am trying to solve this from 2 days.
    Or else can u please show a demo of your tutorial with the code, that would be very useful if u show a demo how it works.

    1. Hi Nirmala,
      Are you trying it on localhost or your live website?
      When you are clicking on link, make sure it passes all parameters and their values such as key, email and action.
      Print their values and match them with that stored in DB.

  3. Hi Javed, this tutorial works good for me, like many others I had the same message “””Mailer Error: SMTP connect() failed.””” and I fixed it with the next steps:

    Here using $mail->Host = “”;
    And adding this line $mail->SMTPAutoTLS = false;

    Additionally I didn’t use the latest version of PHPMailer, I used the files in folder “PHPMailer” you let in the files.

    Thank you so much

  4. i’m getting this error
    Fatal error: Uncaught Error: Class ‘PHPMailer\PHPMailer\PHPMailer’ not found in /var/www/forgot-password.php on line 23
    but working in localhost while i’m going host that getting the error like that
    how to solve this error

  5. Why do you publish code that doesn’t work? The output is always:

    Invalid Link
    The link is invalid/expired. Either you did not copy the correct link from the email, or you have already used the key in which case it is deactivated.

    Click here to reset password.

    I basically copied and pasted your code and wasted 2 hours trying to fix it.

    1. Well my friend, development is not easy as you think. Although i try my best to share the best stuff for free.
      You may be doing something wrong or missing anything which is causing the error.
      Anyhow if you want so i can teach you online if you are ready to pay.

  6. Hi Sir, Thanks for sharing.
    I have encountered the below problem…
    in line 25–>$key = md5(2418*2+$email);
    What should I do?

    Warning: A non-numeric value encountered in /Library/WebServer/Documents/all/user/forget_password.php on line 25
    An email has been sent to you with instructions on how to reset your password.

  7. hi,
    I am using xampp and trying to use this code. I am receiving this error .
    Mailer Error: Could not instantiate mail function. . please help me .I want to run this locally . do not have any domain that’s why want to test locally .


    1. Sir! Plzz solve it …i really need the answer ….Write the source code in PHP, MySQL in which user enter the number, program will reverse the number. After reversing the number, show the sum of all numbers. For example if number is 153, then after reverse it will be 351, and sum will be 9. Now if the sum is an odd number, then store the odd number in a database table1 and store the cube of that odd number in table2.
      Finally show the odd number and its cube from the database with only one query.

  8. Hi Javed, thank you for the tutorial but i can’t seem to find a way around this error “Invalid address: (punyEncode)”

    Kindly assist

  9. i got this error plz help me

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\Login\Forgotpass\index.php on line 28

  10. Hi Javed, your tutorial as been helpful, thanks a lots.

    i encounter a problem while i have done the necessary things you told you said
    on it as been hosted online, and this is all that i got, i have tried as much as possible to rectify them one after the other, but only this were giving me hard time to fix

    Warning: A non-numeric value encountered in /home/mstarzmu/public_html/forget/index.php on line 62

    Deprecated: __autoload() is deprecated, use spl_autoload_register() instead in /home/mstarzmu/public_html/forget/PHPMailer/PHPMailerAutoload.php on line 45

    Warning: stream_socket_enable_crypto(): Peer certificate' did not match expected’ in /home/mstarzmu/public_html/forget/PHPMailer/class.smtp.php on line 354
    Mailer Error: SMTP connect() failed.

  11. Hi javed,
    What if the user did not use the link to reset the password?
    will the data in password_reset_temp get deleted after 24 hrs because if the user clicks the reset password after few days again it messes up while selecting the query

  12. Hii sir, your tutorial is amazing
    but i got one issue that I’m not getting reset password blank page what to do please help me!

    1. Debug the issue, try to echo anything where you think issue could be there, although tutorial is working fine but may be you got error due to some other reason.
      By printing anything on that page you will be able to know that where pointer is stopping.

  13. Hello Javed,

    Hope you are doing fine.
    First, I want to thank you for this amazing tutorial.
    Second, I have implemented on my website and all works except the form to put a new password that does not appear in PC browser (Chrome, IE, Edge…) but it’s appear on smartphone. I have removed the line calling the css file but I still have the same issue. Do you have any idea please ?

    1. Hi Lamine,
      I would suggest you to debug the code by printing anything on the page where it display new password field to make sure that pointer is coming here or not.
      If nothing is printing then something is wrong and pointer is not coming to the right position.

    1. Dear Syakira,
      You are not able to connect with SMTP, make sure you are using correct credentials such as email, password and host for SMTP connection, you may also try to connect with Gmail SMTP.

      1. Hi sir, may i know how to use php code connect with android studio?i hv done create login and register with database but i dont know how to modify a forget password code

      2. I have this same problem and I revised all the credentials and
        I think they are all right, could be the problem that the files for Phpmailer are outdate?

  14. Dear, Javed sir, i have a question.

    $query3 = mysqli_query($db,”UPDATE user_login SET password=’$password’ WHERE = 1″)
    or die(mysqli_error($db));

    this is working only when the id=1 exits in my database.
    If a person enter his/her email , the id may be different na. so how could or what is the expected code to modify so that the the id related to that particular person will be selected. and the person can easily change the password.

    1. make your id dynamic!!
      don’t define manually = 1;
      take your id in a variable and use it there like $mylogId = $row[id]; = $mylogid;

      now this work for all.

  15. Hi Javed. I appreciate your work. It solved a problem I have been struggling with for days. With your help, I have managed to do it.

    I, however, met a problem. I cannot send emails with ‘@gmail’. All emails with my domain are working like charm.

    The emails bounced back.

  16. Hi,

    First just wanted to thank you for this tutorial. This is great! I have 2 probably simple questions.

    1.) Why no id in the password_reset_temp table? Please help me understand this part. Is this because the keys, emails and dates are temporary? Or is it ok to add an id column. Just found this interesting when I tried to delete the test posts and I couldn’t select them in the phpMyAdmin.

    2.) My local host is throwing me this error:
    A non-numeric value encountered error at
    $keyval = md5(2418*2+$email);
    Using php 7.2 and the update from 5* seems to throw this error. Can I remove the $email variable from the hash and will the code still work?

    Thank You

  17. Please sir would you help me with what I am doing wrong. I have your system working to the password-reset.php page….the email delivers it right, and the link expires right, but the passwords do not get changed.

    I have the register database with the tables set up.

    My original download files hosted with the changes to allow for the sql connections is at:
    Thank you so much for your help!!


    Jerritt Pace

    1. Hi Jerritt J Pace,
      Before making any changes into the system, try to download the complete zip file of this tutorial and try to execute that file. If it is working properly then you should make changes. As per your issue, your updating query is not working, i would suggest try to run that query manually at your sql and check is there any syntax issue, if it is working fine then try to run the same query only on separate page and check if that query is working using PHP db connection. If you find that it is working fine the integrate that code in your system.

  18. if code of PHPMailer is working in localhost and not working in main site host, where could be problem
    and site host is saying that it is your programming issue.

  19. Hello Javed,
    Thanks for sharing this wonderful tutorial. This is a very useful and desired feature in the Registration system.

    Just some small suggestion:
    1. Instead of creating a separate DB file password_reset_temp, why not add these three fields i.e. email, key and expDate to the ‘users’ DB file.
    2. Could you be updating your code to support PDO (in the future, may be)

    Once again, a wonderful blog. Keep it up!


  20. Hi

    I absolutely love your tutorials, thank you so much for sharing.

    I have a problem with the forgotten password script. Everything seems to work and i am connecting to the database ok, but i get the ‘No user is registered with this email address!’ message, whether that email exists or not.

    Do you have any advice as to where the problem might be?

    Many thanks


  21. Hi Javed Ur Rehman,

    I am facing Warning: A non-numeric value encountered error at
    $keyval = md5(2418*2+$email);
    $email is the input value and is a string. How can you add a string with a numeric (2418*2)?

  22. 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

  23. 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
    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
        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]

  24. 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.

  25. 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.

  26. 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.

  27. 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.

  28. 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.


    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

    $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!”;
    echo “”.$error.”
    Go Back“;
    $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
    “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.


  30. 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

  31. 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.

  32. 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.

  33. 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.

  34. 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.

  35. if($result){
    echo ”
    You are registered successfully.
    Click here to Login“;
    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

  36. 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…

  37. 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.

  38. 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.

  39. 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 *