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.
- Create a Temporary Token Table
- Create a Database Connection
- Create an Index File (Send Email)
- Create a Reset Password File
- 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> </p>
<p> </p>
<p> </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;
}
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
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);
Replace this $key = md5(2418*2+$email);
With $key = md5(4836+$email);
Thanks Javed. Converted mysqli queries to PDO but haven’t tested it yet. The simple things add up to the big things.
You welcome Mark, I am glad to know that you found my tutorial helpful.
doesn’t work, blank index page install
Dear Roc, can you share more details about the error, on what stage you are getting error?
Thanks so much
You are most welcome Ibrahim.
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
Dear Johnson,
Thanks for your appreciation.
Can u help me in my website
Sure, you can send your query at my email at [email protected]
What date was this code published? I get errors all over it from MD5 and $error in the index file. Thanks.
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);
Anubhav you can replace this unique key with anything. Or you can also concatenate them using php . operator instead of +
Really good article. Scripts and php code very clear and precise. Could replicate without any difficulties in my mvc php framework. Thanks Javed!
Thanks for the appreciation Marco, I am glad that you find it helpful.
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?
Wes Senter,
If you are getting Undefined variable error then declare $error variable in the beginning of the code with empty string. Like this $error = ”;
Thanks for this article helped me see what was lacking in my project
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 ?
thanks for this tutorial it works perfectly for me, but I found it difficult to add your PHP captcha to it. https://www.allphptricks.com/create-a-simple-captcha-script-using-php/
please how can I add the captcha script to the forget password script?
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.
Thank you so much, it works perfectly for me, your tutorials have helped me with my projects, and I appreciate it.
Hi Sanusi Olamilekan,
I am glad that you found my tutorials helpful.
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.
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 🙂
Hi sir …
index.php line no 11 problem here…
and i have nothing solve this problem ….
Dear Ali, kindly share the error message.
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
Dear muaz, replace $key = md5(2418*2+$email); with this $key = md5($email);
there are an error Fatal error: __autoload() is no longer supported, use spl_autoload_register() instead in C:\xampp\htdocs\demo\PHPMailer\PHPMailerAutoload.php on line 45, then I change __autoload() to spl_autoload_register(), after i changed that there are another error Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Use the updated PHP Mailer library, you are using PHP 8 so you will need to download the updated PHP mailer library and use it.
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
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
Just replace this code $key = md5(2418*2+$email); with this $key = md5($email); Hope this will solve your issue.
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.
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.
hi javed, MD5 is not a secure way of hashing passwords.
I suggest using password_hash instead for that purpose.
Yes there are several alternatives to hash password, thanks for your input.
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!
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.
Hi I have a question will this reset password work in local host?
Yes It will
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.
You welcome Adrian, thanks for the appreciation.
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);
You can display anything in your email, you need to make sure that you are fetching the right columns from database table. You can check out my tutorial here about how to view record from database.
https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
Always bind your parameters, never use php variables directly in your SQL queries
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.
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.
Bro I’m working on live website and use your (forgot-reset-password system), but continuously face this error “Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting“…. kindly help me and I need your guidance
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.
Not useful at all
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 😉
I agree with you, prepared statements are the best choice to avoid SQL injections. You can use prepared statements.
Sir everything is fine .. but the new password is not updating in server.. what should I do please help me
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.
Thank you! Worked fine here.
thanks pro
You welcome 🙂
Fatal error: Uncaught TypeError: Unsupported operand types: int + string in
error message i am getting when i try to run the index.php file
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.
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.
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?
You are getting empty data, make sure that you have record in your database and it is fetching it properly.
Why it’s not working for me? Getting error in local host.
Most it is caused by SMTP configuration, I would suggest you to try with Google SMTP too for localhost.
Hi Rehman
I’m using local Mailserver on local host is that compatible with the PHPMailer
If that is sending email then great, if not then you will need to use PHPMailer.
how to collect cart items and insert it in the cart table
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.
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
Hi Daniel, I do not delete token, I simply check if the token was generated before the expire time limit then user can reset password.
Token should not be generated before 1 day.
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.
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.
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
Kindly share what kind of error you are getting.
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.
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.
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?
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.
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.
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.
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
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.
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.
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
Thank You So Much , This Blog Was Helped Me A Lot To Reset Password
Thanks Prema for the appreciation.
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!
Hi Aliyah,
Copy paste the following in the top of the page. error_reporting(0);
I hope this will solve your issue.
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.
Dear Misfar,
Thanks for the appreciation.
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.
Dear Mark, you can use any combination for it.
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.
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.
sir…..
i m facing issue while tying to reset password…
Warning: A non-numeric value encountered in C:\xampp\htdocs\register\reset\index.php on line 39
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
help me to solve this
Your SMTP credentials are incorrect, kindly contact your hosting provider and ask them to provide SMTP credentials for email setting.
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
You welcome Jose.
Hello, i’m not sure why i get this, but i can’t seem to send e-mails to the user. Error is below.
Mailer Error: SMTP Error: The following recipients failed: [email protected]: : Sender address rejected: not owned by user [email protected]
There is error in your SMTP and Sender, Kindly ask SMTP from your hosting provider.
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
Your SMTP is incorrect, ask for SMTP from your hosting provider.
do i need to dwonlod php mailer lib
Yes
Please help me
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Contact your hosting provider and ask them to provide you the correct email credentials for SMTP.
Amazing tutorial, thanks
NO PROBLEMS ENCOUNTERED, THE CODE WORKED SMOOTHLY
Thanks Ramesh for the appreciation.
Warning: A non-numeric value encountered in C:\xampp\htdocs\demo\index.php on line 39
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Check your SMTP credentials.
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.
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.
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.
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
Use Gmail for Localhost, simply use GMAIL SMTP setting, you can easily find it on Google.
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.
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
Contact your hosting provider and ask them to provider correct SMTP credentials for sending email.
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
Your MD5 hash is using a number times a string. PHP is throwing an error.
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
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
Daer Sampath,
Data is not deleting automatically, however you can create your own cron job to delete the data older then 24 hours later.
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!
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.
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 ?
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.
Dear sir, thank you for your great tutorial. everything is fine for me except when I enter my email for password recovery, it has error that says:
Warning: A non-numeric value encountered in C:\xampp\htdocs\demo\index.php on line 39
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
can you please help me sir. thank you in advance.
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.
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
Hi Aisyah, i have never tried to connect it with Android Studio, may be a Google search may help you out.
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?
Yes new version is available of PHPMailer but old one is still working. However, if anyone is not be to proceed with this so can try the updated version of PHPMailer.
Thank you. Good example and easy to fellow.
AHB
Thanks for the appreciation 🙂
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.
Dear Rashmi,
I didn’t use any place the query which you are asking, kindly check my tutorial, i have updated the table using email ID instead of ID.
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.
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.
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
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
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.
The “key” is getting saved as password instead of “new password” in the DB.
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.
Check your email authentication credentials, you can also use gmail for SMTP.
Sir i have created index.php and i am getting forget password link but when i click on the link it does not open
Download my entire tutorial and try to run it on your localhost, just make changes in database configuration
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
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,
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
It seems like your query is not working, check your sql query on phpmyadmin first, then try it on web page.
hi i need simple application add ,read,select ,update, delete records form table through forms. by php and mysql
Hi Raju, check this tutorial https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
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)?
Hi Bala, i am not adding value, i am simply encrypting value.
use . as concatenate instead of + sign
Very nice article. I absolutely love this website.
Stick with it!
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
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
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.
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
Please, sir, grant this request
Amazing tutorial JAVED!
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]
sir, please, i’m getting this error in my reset password file,
Warning: A non-numeric value encountered in C:\Users\USER\Desktop\XAMP only\htdocs\forgotpass\index.php on line 25
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
how do i solve it sir?
You are getting SMTP error, kindly make sure you are using the correct credential. If you are not know how to send email then look at my tutorial here https://www.allphptricks.com/send-email-in-php-using-phpmailer/
thanks sir, God bless you sir, i’ll try, try, try, and keep trying, until we arrive at the right and ideal place
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
Hi Mark, you can find the users table from the download file, kindly download the tutorial extract it and get the user table thanks.
i am trying it, but it’s not working. just error 500
Hello,
My password is reseted with the key. How can I solve that?
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.
hello
I mean. The key it’s saved as password in the DB
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.
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.
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.
You can see that i adding +1 with date(“d”) which means adding 1 day expire you can do the same with minute as well, to increase minutes.
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.
WAS, Dear Sajjid, i hope that i will start sharing tutorials soon. For now search it on Google, hope your problem will be solved.
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.
Dear Hery, i am glad that you found my tutorial helpful.
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.
Hi,
Could you please let me know how i can decrypt the password, so i can login using the changed password.
Thanks!
Hi Dinesh, you can see that i am using md5() to encode and decode password. You can login with your updated password, this system will proceed you with your new password.
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
All values are inserted by user through the form
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
Hi Frank, yes you will need to match all your newly created table column names with the query, if there is any single character error, it will not work. You can also check my tutorial about how to insert into database, hope this will help you.
https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
Good work boss! Keep it up! Thanks for for been there for us.
Thanks Daniel for the appreciation.
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\PHPProjectTest\Admin\ForgotPassword.php on line 142
How to solve it sir??
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.
failed to open PhpMailerAutoload.php error
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?
There is nothing to upload on server, if someone forgot password then user can update or reset password in database. What do you see in your server can you explain?
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
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.
Hi thank you
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
why this error please help me , and i shared your website on social media please help me. . .
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.
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.
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.
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.
There is complete guide how to send email, follow the instruction to send email. https://www.allphptricks.com/send-email-in-php-using-phpmailer/
I could not send the mail below is the error message i got, Kindly help
Mailer Error: SMTP connect() failed.
You need to set up your email account to send email, check my complete tutorial about set up and sending email. https://www.allphptricks.com/send-email-in-php-using-phpmailer/
I am unable to send the mail what is the problem
Dear Sujendra, i have shared complete tutorial about how to send email, you should check this out, hope this will help you. https://www.allphptricks.com/send-email-in-php-using-phpmailer/
Warning: A non-numeric value encountered in index.php on line 25,why so?
Well, this code is working fine for mostly people, may be you will need to tell more about your problem so that i can help you out.
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
Dear Neha,
Move the session_start(); at the beginning of each page it exist. Issue will resolved.
i already subscribed but i can not download aby361008@gmail
Try again after refreshing web page.
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…
Dear Aakash, it seems like that you have already declared PHPMailer, kindly check if you have declared it before?
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 ?
Just make sure that the file are exist in the same location that you are giving in require() function.
Sir Good day is this working in local host…..im just a newbie and im trying using it with xamp ?
I prefer that you test email on web host, i didn’t test it on localhost so may be you will need to do extra work to get it working on local.
Hi Sir!
Your content is really helpful. Kindly write a blog on how we show all user list only with the admin.
Thanks Zahid.
You can list all user/data from database by following my tutorial https://www.allphptricks.com/insert-view-edit-and-delete-record-from-database-using-php-and-mysqli/
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
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.
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.
Sanjay i have shared a separate tutorial of dynamic dependent selectbox, kindly check it. This will help you.
Can i get to learn web development from you sir, especially PHP and SQL sir?
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
BestTutorial