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

Readers Also Read: Laravel 10 User Roles and Permissions

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.

CREATE TABLE `password_reset_temp` (
  `email` varchar(250) NOT NULL,
  `key` varchar(250) NOT NULL,
  `expDate` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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.

$con = mysqli_connect("localhost","root","","register");
    if (mysqli_connect_errno()){
	echo "Failed to connect to MySQL: " . mysqli_connect_error();
	die();
	}

date_default_timezone_set('Asia/Karachi');
$error="";

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.

<?php
include('db.php');
if(isset($_POST["email"]) && (!empty($_POST["email"]))){
$email = $_POST["email"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) {
   $error .="<p>Invalid email address please type a valid email address!</p>";
   }else{
   $sel_query = "SELECT * FROM `users` WHERE email='".$email."'";
   $results = mysqli_query($con,$sel_query);
   $row = mysqli_num_rows($results);
   if ($row==""){
   $error .= "<p>No user is registered with this email address!</p>";
   }
  }
   if($error!=""){
   echo "<div class='error'>".$error."</div>
   <br /><a href='javascript:history.go(-1)'>Go Back</a>";
   }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."');");

$output='<p>Dear user,</p>';
$output.='<p>Please click on the following link to reset your password.</p>';
$output.='<p>-------------------------------------------------------------</p>';
$output.='<p><a href="https://www.allphptricks.com/forgot-password/reset-password.php?
key='.$key.'&email='.$email.'&action=reset" target="_blank">
https://www.allphptricks.com/forgot-password/reset-password.php
?key='.$key.'&email='.$email.'&action=reset</a></p>';		
$output.='<p>-------------------------------------------------------------</p>';
$output.='<p>Please be sure to copy the entire link into your browser.
The link will expire after 1 day for security reason.</p>';
$output.='<p>If you did not request this forgotten password email, no action 
is needed, your password will not be reset. However, you may want to log into 
your account and change your security password as someone may have guessed it.</p>';   	
$output.='<p>Thanks,</p>';
$output.='<p>AllPHPTricks Team</p>';
$body = $output; 
$subject = "Password Recovery - AllPHPTricks.com";

$email_to = $email;
$fromserver = "[email protected]"; 
require("PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.yourwebsite.com"; // Enter your host here
$mail->SMTPAuth = true;
$mail->Username = "[email protected]"; // Enter your email here
$mail->Password = "password"; //Enter your password here
$mail->Port = 25;
$mail->IsHTML(true);
$mail->From = "[email protected]";
$mail->FromName = "AllPHPTricks";
$mail->Sender = $fromserver; // indicates ReturnPath header
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($email_to);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "<div class='error'>
<p>An email has been sent to you with instructions on how to reset your password.</p>
</div><br /><br /><br />";
	}
   }
}else{
?>
<form method="post" action="" name="reset"><br /><br />
<label><strong>Enter Your Email Address:</strong></label><br /><br />
<input type="email" name="email" placeholder="[email protected]" />
<br /><br />
<input type="submit" value="Reset Password"/>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<?php } ?>

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.

<?php
include('db.php');
if (isset($_GET["key"]) && isset($_GET["email"]) && isset($_GET["action"]) 
&& ($_GET["action"]=="reset") && !isset($_POST["action"])){
  $key = $_GET["key"];
  $email = $_GET["email"];
  $curDate = date("Y-m-d H:i:s");
  $query = mysqli_query($con,
  "SELECT * FROM `password_reset_temp` WHERE `key`='".$key."' and `email`='".$email."';"
  );
  $row = mysqli_num_rows($query);
  if ($row==""){
  $error .= '<h2>Invalid Link</h2>
<p>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.</p>
<p><a href="https://www.allphptricks.com/forgot-password/index.php">
Click here</a> to reset password.</p>';
	}else{
  $row = mysqli_fetch_assoc($query);
  $expDate = $row['expDate'];
  if ($expDate >= $curDate){
  ?>
  <br />
  <form method="post" action="" name="update">
  <input type="hidden" name="action" value="update" />
  <br /><br />
  <label><strong>Enter New Password:</strong></label><br />
  <input type="password" name="pass1" maxlength="15" required />
  <br /><br />
  <label><strong>Re-Enter New Password:</strong></label><br />
  <input type="password" name="pass2" maxlength="15" required/>
  <br /><br />
  <input type="hidden" name="email" value="<?php echo $email;?>"/>
  <input type="submit" value="Reset Password" />
  </form>
<?php
}else{
$error .= "<h2>Link Expired</h2>
<p>The link is expired. You are trying to use the expired link which 
as valid only 24 hours (1 days after request).<br /><br /></p>";
            }
      }
if($error!=""){
  echo "<div class='error'>".$error."</div><br />";
  }			
} // isset email key validate end


if(isset($_POST["email"]) && isset($_POST["action"]) &&
 ($_POST["action"]=="update")){
$error="";
$pass1 = mysqli_real_escape_string($con,$_POST["pass1"]);
$pass2 = mysqli_real_escape_string($con,$_POST["pass2"]);
$email = $_POST["email"];
$curDate = date("Y-m-d H:i:s");
if ($pass1!=$pass2){
$error.= "<p>Password do not match, both password should be same.<br /><br /></p>";
  }
  if($error!=""){
echo "<div class='error'>".$error."</div><br />";
}else{
$pass1 = md5($pass1);
mysqli_query($con,
"UPDATE `users` SET `password`='".$pass1."', `trn_date`='".$curDate."' 
WHERE `email`='".$email."';"
);

mysqli_query($con,"DELETE FROM `password_reset_temp` WHERE `email`='".$email."';");
	
echo '<div class="error"><p>Congratulations! Your password has been updated successfully.</p>
<p><a href="https://www.allphptricks.com/forgot-password/login.php">
Click here</a> to Login.</p></div><br />';
	  }		
}
?>

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.

.error p {
	color:#FF0000;
	font-size:20px;
	font-weight:bold;
	margin:50px;
	}

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

Twitter 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. Forgot Password Recovery (Reset) using PHP and MySQL with otp generated through email and reset new password while 30 seconds counter timer set and if otp has been enter while expired the it go to change to New Password and login with New Change Password in php and mysql.. Please Help use and solve my issues ..

  2. Getting the following error:

    Demo Forgot Password Recovery (Reset) using PHP and MySQL

    Fatal error: Uncaught TypeError: Unsupported operand types: int + string in C:\xampp\htdocs\forgot-password\index.php:39 Stack trace: #0 {main} thrown in C:\xampp\htdocs\forgot-password\index.php on line 39

    Line 39 of index.php says: $key = md5(2418*2+$email);

  3. Hi Mr. Javed. I can not just read code and benefited in this tutorial without saying a word of thanks. All your works are Well done and benefited to me. Thanks.

    Johnson J. D

  4. What date was this code published? I get errors all over it from MD5 and $error in the index file. Thanks.

  5. Demo Forgot Password Recovery (Reset) using PHP and MySQL

    Fatal error: Uncaught TypeError: Unsupported operand types: int + string in C:\xampp\htdocs\demo\index.php:39 Stack trace: #0 {main} thrown in C:\xampp\htdocs\demo\index.php on line 39

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

  6. Really good article. Scripts and php code very clear and precise. Could replicate without any difficulties in my mvc php framework. Thanks Javed!

  7. Hello Javed,

    This is a very good script you have created. I have it working with my template for appearence but I have one issue I can’t seem to figure out. The php script runs fine, all the way through but it does not update the password in the user table. I get this error: [20-Jul-2023 14:48:11 UTC] PHP Notice: Undefined variable: error in /home/land9880/public_html/resetPassword.php on line 149. Here is the code on that line.

    <?php

    } else {
    $error .= "Link Expired
    The link is expired. You are trying to use the expired link which
    as valid only 24 hours (1 days after request).”;
    }
    }
    Line 149 -> if($error != “”){
    echo “”.$error.””;
    }
    } // isset email key validate end

    Can you possibly suggest anything?

  8. Hello. The script look excellent but I have problem with the script
    Warning: Undefined variable $error in…..forgotPass.php on line 177

    The line show
    if($error!=””){

    The other error is
    Fatal error: Uncaught Error: Class “PHPMailer” not found in forgotPass.php on line 210
    The line show
    $mail = new PHPMailer();

    Any help Please on this ?

    1. Dear Sanusi,
      I would suggest you first try to download my PHP captcha script and run it separately, If you successfully able to use it then you can integrate it with your forgot password in PHP.

      1. Thank you so much, it works perfectly for me, your tutorials have helped me with my projects, and I appreciate it.

  9. There is not any security on this.
    Anyone that has an account and can reset their password can see the form.
    Then, they can reset any other user’s password that they know the email of.
    The key needs to be added to the form as a hidden field and the update should only take place after validating the key.

    1. Dear Nate,
      Thanks for your input, in this tutorial. I am trying to show the process of forgot password with the minimum code to keep it simple. However, you can easily place the encryption to make it more secure, you use use encryption and decryption function to encrypt email and key. And make sure that you set your own secret key in encryption function.
      You can check out my tutorial about encryption and decryption in PHP here https://www.allphptricks.com/how-to-encrypt-decrypt-string-in-php/
      Hope this will solve your issue.
      Happy Coding 🙂

  10. Hi sir, there have an error when using PHP version: 8.0.25, Fatal error: Uncaught TypeError: Unsupported operand types: int + string in C:\xampp\htdocs\demo\index.php:39 Stack trace: #0 {main} thrown in C:\xampp\htdocs\demo\index.php on line 39

          1. I have updated PHP Mailer library but have an error, Fatal error: Uncaught Error: Class ‘PHPMailer’ not found in C:\xampp\htdocs\demo\index.php:65 Stack trace: #0 {main} thrown in C:\xampp\htdocs\demo\index.php on line 65

  11. I keep geting this error everytime I try to run this code

    Demo Forgot Password Recovery (Reset) using PHP and MySQL

    Fatal error: Uncaught TypeError: Unsupported operand types: int + string in C:\xampp\htdocs\app\admin\demo\index.php:39 Stack trace: #0 {main} thrown in C:\xampp\htdocs\app\admin\demo\index.php on line 39

  12. Fatal error: Uncaught TypeError: Unsupported operand types: int + string in C:\xampp\htdocs\demo\index.php:39 Stack trace: #0 {main} thrown in C:\xampp\htdocs\demo\index.php on line 39

    how can I fix this? it seems like it’s part in your tutorials and code.

    1. If you are facing issue then you should replace this $key = md5(2418*2+$email);
      on index.php
      with your own custom key, it can be anything combine anything or any unique characters with your email and then encrypt them either using md5 or any hash function.

      1. hi javed, MD5 is not a secure way of hashing passwords.
        I suggest using password_hash instead for that purpose.

  13. Hi Javed, thank you for this tutorial. I have been trying to implement it for days now though. Fortunately I finally have been able to send an email with a link. (Apparently I needed a newer version of PHPMailer and had to add some lines to the code.) But now the next challenge is to make the link work. When user clicks on link, the page is empty. Also, I do not see any error nor do I receive any logs. I’ve even added:
    ini_set(‘display_errors’, 1);
    ini_set(‘display_startup_errors’, 1);
    error_reporting(E_ALL);
    to reset-password.php, but I still don’t see any errors. I have no idea what’s wrong here. Do you have any idea? I would appreciate your help. Thanks!

    1. Hi Rone, when the user click on email link, then it comes with some parameters like key, email, action, I would suggest you to echo all these GET parameters value and make sure that you are able to receive them on your page reset-password.php, after that make sure that your database query is also working on the same page. We do match the key and email in database password temp table, when it is matched, then you can enter new password. Hope this will help you.

  14. Thank you very much for your excellent tutorial. Our website had a user account system with no password reset mechanism and your code examples were just what I needed to add one.

    All your code worked perfectly and I just had to change field names etc, thanks again.

  15. Hello, first of all I’d like to thank you for your tutorial and if you can help me about to insert the name of the user in the email like this:
    Congratulations user “username”!

    So the “username” and “email” are in the same table called “users” and another “email” in the table “password_reset_temp”.
    How can I put the username associated to the email?
    I just made this but do not work:
    $calluser = “SELECT `email` FROM `users` WHERE username='”.$username.”‘”;
    $resultuser = mysqli_query($calluser);
    $username = mysqli_query($resultuser);

  16. Thank you for your tutorials!

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

    The mail sends well, but upon clicking the link I get the above error.

    1. It seems like either there is issue in your system and server time setting. You will need to debug the code by using echo to check what is current system time and what is time in your database. If there is no time error then you can debug other things. You will need to echo everything in PHP conditions to find out issue on your side.

    1. Waqas, you need to contact your hosting provider and get the SMTP credentials. Additionally, I will suggest you to use the updated PHP Mailer library which you get download from the Github of PHPMailer.

  17. You really shouldn’t throw an error like “invalid email”. It lets attackers know what emails are valid users and what are not. Just say the reset link was sent regardless.

    Also skeeves me out to see someone directly injecting strings into SQL statements like that. Yes, you filtered the input to be a valid email, but apostrophe is a legal character for email addresses per RFC 3696. Join the rest of us in the modern age of prepared statements 😉

  18. Sir everything is fine .. but the new password is not updating in server.. what should I do please help me

    1. You can debug the code by checking either updating query is working directly when you run it through phpmyadmin, if it is working fine then make sure that your database connection is working on that specific page where you are running update password query.

  19. Fatal error: Uncaught TypeError: Unsupported operand types: int + string in
    error message i am getting when i try to run the index.php file

  20. I’m facing the same problem. When I click the link sent to my email to reset my password, it works when I’m using my mobile device but when using my laptop or desktop, it displays just a blank page. The form to reset the password is not shown. Please help me.

    1. Dear Samson,

      If application is not working on laptop then usually, It should not work on mobile as well. Anyhow, I will suggest you to print all those values that we are getting after email verification to check out if values are passing correctly. You can use echo to print values.

      1. Dear Javed,
        I have tried your code but, always it says No user is registered with this email address! can you help me to solve this?

      1. Hi Rehman

        I’m using local Mailserver on local host is that compatible with the PHPMailer

          1. Cart items are already in array, you can simply insert them into database. Just execute the loop through array and insert all of them into cart table. You can check out my tutorial how to insert edit delete record.

  21. Could you please explain to me, how does it work with the expiration Date, which deletes the generated token after one day passed without action?
    Thank you, btw loved your tutorial

  22. I think there is a major security issue with this code… You could easily reset the password of any email by submitting a POST to ‘reset-password.php’.

    The ‘key’ value from the GET should also be included and validated (again) in the POST before accepting the new password.

    This is the annoying thing with the web. No matter how many validations you do beforehand (PHP and JavaScript), you still need to re-validate everything just before the intended action since the request (GET or POST) can come from anywhere, not necessarily the previous page you’re expecting it from.

    And the md5 hash should no longer be used to store password.

    1. Hi thanks for you input, we are already validating email and key value before setting new password, every time a unique key is generated and sent to user’s email. No one can reset password just by email only, they also need this unique which is only available to user’s email.
      Although, I agree that there are several things you can do to make it more secure. However, the purpose of this tutorial is to explain the password resetting, instead of making password strong and secure.

  23. Hi,
    I’m facing some issues with the code while I enter the email and try to reset it, the reset password code is not working properly could you please help in re solving this issue.
    Thank you

      1. Hi, I have the exact same issue. I receive the message ” Congratulations! Your password has been updated successfully.” but the nex password doesn’t work and the old one is still working.

        1. It seems like update query is not working, kindly make sure that your database connection is working, try to debug the code, execute the query directly on SQL to check if it is working then echo some data from database to check connectivity and echo the update query at the time of execution.

  24. Hello, i read this tutorial and it did help me a lot. But i did find some security issues, for example you have not prepared the sql querys. wich makes it pretty easy for hackers to use sql injections. And u used $_GET in the reset-password.php. Can you explain why u used $_GET and not $_POST?

    1. I tried to keep it simple as possible you can implement prepared sql or PDO.
      As for as GET is concerned we can not use post method when user click on link on his email. We can only use Get methods to fetch the parameters of URL through URL.

  25. Hi, I manage to use the tutorial. Thank you very much. Unfortunately, after user change the password, the password is not correct. The password had change but not follow user input.

    1. First check the database, if it is updated, then print the entered user and password after form submit to check if it is correct. After that you can query the same on MySQL to check if there is any record exist with the same credentials.

      1. sir. i faced the same error and when i remove MD5 i can login with the password. i have reversed md5 code in database and it is the same as what i entered. but when with md5 code, they say its wrong

  26. Thank you for this!
    Can you please make a tutorial on how to make an “remember me” function on login-page and a function where users have to activate their account by a confirmationlink sent to their email.

    1. Hi Peter, for activation you can add column in your database with any name, such as activate and initially it will have 0 value, once the user click on link which we sent on email, you can simply update the user record and set activate column value to 1. Hope this will help you out, and for remember me, simply create a cookie and store in browser for any time period that you like.

  27. Hi Javed

    Thank you for publishing this tutorial. I downloaded the package and made the necessary updates. I’m however getting an error msg saying: “No user is registered with this email address!” when I try to reset the user password. I have confirmed via phpMyAdmin that the user exists in the database using that very query. Any ideas what is happening and how to address it? thx

  28. Hi! First of all, thank you for this helpful tutorial. However, I always encounter this warning message “Warning: A non-numeric value encountered in C:\xampp\htdocs\demo\index.php on line 39” even if the code is already working. Any solutions on how the warning message can be removed? Thank you!

  29. Thanks a lot. I am really very glad to post this comment. This blog helped me a lot to come out password reset problem. Thank you very much. Keep going on doing like this good things. God bless you.

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

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

  32. 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 = “smtp.myemail.com”;
    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

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

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

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

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

    Thanks

    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.

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

    Kindly assist

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

  39. 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 https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/ 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 CN=`standard12.doveserver.com’ did not match expected CN=`mail.mstarzmusic.com’ in /home/mstarzmu/public_html/forget/PHPMailer/class.smtp.php on line 354
    Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

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

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

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

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

    $query3 = mysqli_query($db,”UPDATE user_login SET `password`=’$password’ WHERE `user_login`.`id` = 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 login.id = 1;
      take your id in a variable and use it there like $mylogId = $row[id];

      login.id = $mylogid;

      now this work for all.

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

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

  46. 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:
    CODE
    Thank you so much for your help!!

    Cheers,

    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.

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

  48. Sir i have created index.php and i am getting forget password link but when i click on the link it does not open

      1. sir every thing is ok i get reset password link on email but when i click on the reset link it shows 403 page error

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

    Regards,

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

    Martyn

  51. 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)?

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

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

      1. thanks sir, God bless you sir, i’ll try, try, try, and keep trying, until we arrive at the right and ideal place

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

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

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

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

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

  59. Hi,

    Could you please let me know how i can decrypt the password, so i can login using the changed password.

    Thanks!

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

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

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

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

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

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

  66. I could not send the mail below is the error message i got, Kindly help

    Mailer Error: SMTP connect() failed.

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

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

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

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

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