In this tutorial, we are going to discuss How to recover the registered users forget password recovery using PHP and MySQL. Here I have shared simple hash email recovery function. Let's see deep discussion.
Before starting this script you must know about login and signup process. For reference check our below to related tutorials.
Database
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(100) NOT NULL `password` varchar(250) NOT NULL, `active_code` varchar(300) NOT NULL PRIMARY KEY (`id`) )
Index.php - Html & Ajax
Make a simple form with on field for email address. After submitting form value check whether that user already registers or not. if email id exists create one random number send email and store active_code column that random value.
<form class="form-horizontal" action="#" id="form_reset_pwd"> <label class="col-sm-3 control-label">Email :</label> <input type="text" class="form-control required email" name="email" placeholder="Email"/> <button type="button" class="forgot_password">Send Email</button> </form> <script type="text/javascript"> $(document).on('click','.forgot_password',function(){ var url = "reset_password.php"; if($('#form_reset_pwd').valid()){ $.ajax({ type: "POST", url: url, data: $("#form_reset_pwd").serialize(), // serializes the form's elements. success: function(data) { if(data==1) { $('#error_result').html('Check your email'); } else { $('#error_result').html('Invalid email id. Please check your email id.'); } } }); } return false; }); </script>
Reset_password.php
Make sure your file in online because of email version code support in server only local mail it will support.<?php $db = new mysqli('localhost', 'root', '', 'mostlikers'); if($_POST['email']!=""): $email=mysqli_real_escape_string($db,$_POST['email']); $db_check=$db->query("SELECT * FROM `users` WHERE email='$email'"); $count=mysqli_num_rows($db_check); if($count==1) : $row=mysqli_fetch_array($db_check); $active_code=md5(uniqid(rand(5, 15), true)); $link = 'http://demos.mostlikers.com/password-reset/change_password.php?
user_id='.$row['id'].'&key='.$active_code; $fetch=$db->query("UPDATE `users` SET `active_code` = '$active_code'
WHERE `email`='$email' "); $to="$email"; //change to ur mail address $strSubject="Mostlikers | Password Recovery Link"; $message = '<p>Password Recovery Link : '.$link.'</p>' ; $headers = 'MIME-Version: 1.0'."\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n"; $headers .= "From: info@mostlikers.com"; $mail_sent=mail($to, $strSubject, $message, $headers); if($mail_sent) echo 1; else echo 0; else : echo 0; endif; else : header("Location:index.php"); endif; ?>
After user getting a password reset link page will redirect to the change_password.php. Here we need to check whether that email and activation present in a database.
Change_password.php - PHP code
<?php $db = new mysqli('localhost', 'root', '', 'mostlikers'); if($_GET['user_id']!="" && $_GET['key']!=""): $user_id=mysqli_real_escape_string($db,$_GET['user_id']); $active_code=mysqli_real_escape_string($db,$_GET['key']); $fetch=$db->query("SELECT * FROM `users` WHERE id='$user_id'
AND `active_code` = '$active_code'"); $count=mysqli_num_rows($fetch); if($count!=1) : header("Location:index.php"); endif; else : header("Location:index.php"); endif; ?>
Change_password.php - HTML & AJAX
<form method="post" autocomplete="off" id="password_form"> <label>New Password</label> <input type="password" id="passwords" name="password" class="form-control required"> <label>Confirm password</label> <input type="password" id="cpassword" name="cpassword" equalto="#passwords"
class=" required" value=""> <div id="error_result"></div> <input type="hidden" name="id" value="<?php echo $user_id; ?>" id="id"> <button type="submit" id="btn-pwd" class="btn btn-primary">Submit</button> </form> <script type="text/javascript"> $(document).on('click','#btn-pwd',function(){ var url = "new_password.php"; if($('#password_form').valid()){ $.ajax({ type: "POST", url: url, data: $("#password_form").serialize(), success: function(data) { if(data==1) { $('#error_result').html('Password reset successfully.'); window.setTimeout(function() { window.location.href = 'index.php'; }, 2500); } else { $('#error_result').html('Password reset failed. Enter again.'); } } }); } return false; }); </script>
New_password.php
update particular user table password column to the new password and active_code column empty.
<?php $db = new mysqli('localhost', 'root', '', 'mostlikers'); if($_POST['password']!=""): $pass_encrypt=md5(mysqli_real_escape_string($db,$_POST['password'])); $user_id=mysqli_real_escape_string($db,$_POST['id']); $fetch=$db->query("UPDATE `users` SET `password` = '$pass_encrypt',
`active_code`='' WHERE id='$user_id'"); if($fetch): echo 1; else : echo 0; endif; else : header("Location:index.php"); endif; ?>
Thank you for visiting. if have any queries write your comments below.
- Albert Einstein
I didn't receive any activation code but am able to change the password..
ReplyDeleteCheck your email spam/junk folder.
DeleteNice tutorial :)
ReplyDeleteOnly i wonder, how do i use this when i have it by php 5.5 password hashing on database?
Thanks for your comment. I will post about php 5 password hash function currently follow the refernce code
Delete$pass_encrypt = password_hash($_POST['password'], PASSWORD_BCRYPT);
// Insert $pass_encrypt into database against user
Login page code
// Fetch hash+salt from database, place in $pass_encrypt variable
// and then to verify $_POST['password']:
if (password_verify($_POST['password'], $pass_encrypt)) {
// Verified
}
So erm.......
Deleteif($_POST['email']!="" && $_POST['password']!=""):
extract($_POST);
$email=mysqli_real_escape_string($db,$_POST['email']);
$pass_encrypt = password_hash($_POST['password'], PASSWORD_BCRYPT);
$fetch=$db->query("SELECT email, password FROM `users` WHERE 'email' = '$email' AND `password` = '$pass_encrypt'");
$count=mysqli_num_rows($fetch);
Where do i place that
if (password_verify($_POST['password'], $pass_encrypt)) {
// Verified
}
In my code?
That is btw the login.php file.
Oops.....better to post the whole code xD
Deletesession_start();
if($_POST['username']!="" && $_POST['password']!=""):
extract($_POST);
$username=mysqli_real_escape_string($db,$_POST['username']);
$pass_encrypt=password_hash($_POST['password'], PASSWORD_BCRYPT);
$fetch=$db->query("SELECT * FROM `users` WHERE email='$username' AND `password` = '$pass_encrypt'");
$count=mysqli_num_rows($fetch);
if($count==1) :
$row=mysqli_fetch_array($fetch);
$_SESSION['login_username']=$row['id'];
echo 1;
else :
echo 0;
endif;
else :
header("Location:index.php");
endif;
This is what i have atm, at the login.php file. That comes along with the download.
Yes This code for login.php file. After user submit the login from make password hash
Deleteif (password_verify($_POST['password'], $pass_encrypt)) {
// Verified
}
I wanted to say, it is saver to make an connection to a database from a different file.
ReplyDeleteAlso because, you use php as file extension anyways.
So you could call the database connection file with: include 'filename';
Greets Tightis
sure
DeleteThis really helped me, but I'm having problem in change_password.php , after I click the link that was sent to my email, it will direct me to change_password.php right? And it will allow me now to set my new password, but I tried and when I click "submit", it just reloads the page, no error. Can u explain how did it happen and what might be the wrong is?
ReplyDeleteHi Louie,
DeleteI have checked live demo it's working fine. Share your verification link. change_password.php page code
great tutorial - thank you ! Would it be worth deleting the active code from the users record in the database so that the email reset link wont work again until the user requests a new password reset link?
ReplyDeletehalo bro, why i always notif "Invalid email id. Please check your email id." but, i this my insert form is great e-mail.
ReplyDeleteplesese help bro, thank before it
i think script is outdated its not working on server
ReplyDeleteHi, Can this codes work on a localhost?
ReplyDelete