Reset Password With Email Using Ajax In PHP - onlyxcodes

Monday 9 November 2020

Reset Password With Email Using Ajax In PHP

In this tutorial, we're going to see reset password with email using Ajax in PHP. On our website, some people sometimes forget their passwords. We are meant to forget the password features on our website for those members.


There are plenty of ways to use a forgotten password. You've already seen several of them. But, I use an email-based system that is popular on most websites.


Using the $.ajax() procedure, I have gained this feature. We can send user requests on the back-end side PHP using this technique and get responses without reloading the page.


Let's make this feature. I assume you already have a user login system on your website. If not, then read mine PHP PDO Login and Register Script With MySQL post that fully covers both login & signup codes.

Reset Password With Email Using Ajax In PHP | Onlyxcodes

Project Structure

See the structure of the project folder below, saved in the C:\xampp\htdoc directory path. Since I have the XAMPP server mounted on the C drive.


Note: Install this project in the www folder if you use the WAMP server.


xampp/
├── htdocs/
	├── Reset-Password-With-Email-Ajax-PHP/
		├── bootstrap/
			├── css/
			│	└── bootstrap.min.css
			├── js/
			│	└── bootstrap.min.js
			├── fonts/
			│	└── glyphicons-halflings-regular.eot
			│	└── glyphicons-halflings-regular.svg
			│	└── glyphicons-halflings-regular.ttf
			│	└── glyphicons-halflings-regular.woff
			│	└── glyphicons-halflings-regular.woff2
		├── js/
		│	└── jquery-1.12.4-jquery.min.js
		├── smtp
		
dbconfig.php
index.php
reset_password.php
send_email.php
update_password.php

Database And Table

First, build the "reset_password_db" called database in your PhpMyAdmin and import the below SQL code to create the user table with the appropriate fields.


Here,


I have one dumping record already installed. We would assume that this hamid-named user email address was used when he signed up for our website. Because this project requires the user to be already on the system to sign up.


Note – I filled out the password and password confirmation column from the tutorial PHP login signup with MySQL that was guided by the password_hash() function. I randomly filled the token column and set the status value placed to 1.


--
-- Table structure for table `user`
--

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `cpassword` varchar(255) NOT NULL,
  `token` varchar(100) NOT NULL,
  `status` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`user_id`, `username`, `email`, `password`, `cpassword`, `token`, `status`) VALUES
(1, 'hamid', '[email protected]', '$2y$10$VGXPhbba/mkp0bKfw/SGM.2A6AnMOgEDR0uUXkdEYsTxOfiwX6eSm', '$2y$10$Kipg2Z5w/J/Zvfai8S9nVusOhLSZOL9O2ngWH8EL2KB.cnERW./V6', 'f80bd93a5cc4c60fa3e034fa481ff8', 1);


dbconfig.php

We configure the database connection in this file with the PDO extension, simply wrapping up the codes below.


If you're using another database, change the name of the database to the $db_name variable.


<?php

$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="reset_password_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>


index.php

This file displays a form that uses email to describe a user account. This request form is forwarded using the $.ajax() procedure.


<div id="msg">
<?php
session_start();
if(isset($_SESSION["errorMsg"]))
{	
?>
	<div class="alert alert-danger">
		<button type="button" class="close" data-dismiss="alert">&times;</button>
		<strong><?php echo $_SESSION["errorMsg"]; unset($_SESSION["errorMsg"]);?></strong>
	</div> 
<?php	
}
if(isset($_SESSION["successMsg"]))
{
?>
	<div class="alert alert-success">
		<button type="button" class="close" data-dismiss="alert">&times;</button>
		<strong><?php echo $_SESSION["successMsg"]; unset($_SESSION["successMsg"]); ?></strong>
	</div>
<?php
}
?>   
</div>

<center><h3>Enter Email And Recover Your Account</h3></center>
<form method="post" class="form-horizontal">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Email</label>
	<div class="col-sm-6">
	<input type="text" id="txt_email" class="form-control" placeholder="enter email" />
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-9 m-t-15">
	<input type="submit" id="btn_send" class="btn btn-success" value="Send Mail">
	</div>
	</div>
					
</form>

ajax code

Before closing the < /html > tag on the index.php page, jQuery and Ajax code will started.


This code is responsible for submitting the form request through the $.ajax() method to the "send_email.php" page. And inside the "#msg" div, it will display a response message.


The code properly checks the validation of the email format and also checks the non-empty email text box value. If any, then the alert() method shows a simple dialogue box on the header section with the relevant message.


<script type="text/javascript">	
$(document).ready(function(){
	$(document).on("click", "#btn_send", function(e){	
					
		var email = $("#txt_email").val();
		var atpos = email.indexOf("@");
		var dotpos = email.lastIndexOf(".com");
				
		if(email == ""){
			alert("Please Enter Email Address"); 
		}
		else if(atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
			alert("Please Enter Valid Email Address !"); 
		}
		else{
			$.ajax({
				url: "send_email.php",
				method: "post",
				data: {uemail:email},
				success: function(response){
					$("#msg").html(response);
				}
			});	
		}	
	});		
});
</script>

send_email.php

Involves only PHP code, This will verify users' registered email in the user table, this file will act peacefully at the back-end and call using jQuery code with $.ajax() process.


If the email was present in the table, the reset password API link will be sent to his / her registered email account to reset his / her password and forwarded it to the "reset_password.php" page with localhost URL like http://localhost/project/reset_password.php?token=" code".


The token code in QueryString is the token value of the database field and we will get this token code in the "reset_password.php" page and verify that the token is correct and allows the user to change their passwords.


I've used PHPMailer to send emails with your localhost server using Gmail SMTP.


<?php
session_start();
require_once "dbconfig.php";

// Get user enter email via $.ajax() method
if(isset($_POST['uemail']))	
{
	$email = strip_tags($_POST["uemail"]);	

	// Select email from the user table 
	$select_stmt=$db->prepare("SELECT * FROM user WHERE email=:user_email");  
	$select_stmt->execute(array(":user_email"=>$email));	
	$row=$select_stmt->fetch(PDO::FETCH_ASSOC);
			
	if($select_stmt->rowCount() > 0)	
	{
		// If email present in the table, then sends email to user mailbox / junk box
		if($email==$row["email"]) 
		{
			$dbusername = $row["username"]; 
			$dbtoken = $row["token"];

			// They can click on this link to reset the password with the token. 
			$reset_link = "Hi, $dbusername. Click here to reset your password
			http://localhost/Reset-Password-With-Email-Ajax-PHP/reset_password.php?token=$dbtoken";
					
			// Send email code
			require_once('smtp/PHPMailerAutoload.php');
					
			$mail=new PHPMailer(true);
			$mail->isSMTP();
			$mail->Host="smtp.gmail.com";
			$mail->Port=587;
			$mail->SMTPSecure="tls";
			$mail->SMTPAuth=true;
			$mail->Username=""; //Enter your gmail id
			$mail->Password=""; //Enter your gmail password
			$mail->SetFrom(""); //Enter your gmail id
			$mail->addAddress($email);
			$mail->IsHTML(true);
			$mail->Subject="Reset Password";
			$mail->Body = ($reset_link);
			$mail->SMTPOptions=array('ssl'=>array(
						'verify_peer'=>false,
						'verify_peer_name'=>false,
						'allow_self_signed'=>false
					));
			if($mail->send())
			{
				$_SESSION["successMsg"] = "email send check your mail box";
				header("location:index.php");
			}
			else
			{
				echo "Mailer Error: " . $mail->ErrorInfo;
			}
		}
		else
		{
			$_SESSION["errorMsg"]="email not found";
			header("location:index.php");
		}
	}
	else
	{
		$_SESSION["errorMsg"]="wrong email";
		header("location:index.php");
	}			
}
?>

reset_password.php

When the user clicks on the reset password API link in their mailbox, this page will be loaded. To update or make a new password, a form will appear and the form request is submitted using the $.ajax() process.


See one input hidden tag before closing the < /form > tag and in this tag we get the token value that came from the QueryString URL when the user clicked on the link.


This token value is used to submit the page "update_password.php" via the ajax method and to update the database password.


<div id="msg">
<?php
if(isset($_SESSION["updateMsg"]))
{
?>
	<div class="alert alert-success">
		<button type="button" class="close" data-dismiss="alert">&times;</button>
		<strong><?php echo $_SESSION["updateMsg"]; unset($_SESSION["updateMsg"]);?></strong>
	</div>
<?php
}
?>   
</div>

<center><h3>Create New Password</h3></center>
<form method="post" class="form-horizontal">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Password</label>
	<div class="col-sm-6">
	<input type="password" id="txt_password" class="form-control" placeholder="new passowrd" />
	</div>
	</div>
				
	<div class="form-group">
	<label class="col-sm-3 control-label">Confirm Password</label>
	<div class="col-sm-6">
	<input type="password" id="txt_cpassword" class="form-control" placeholder="confirm passowrd" />
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-9 m-t-15">
	<input type="submit" id="btn_update" class="btn btn-primary" value="Update">
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-9 m-t-15">
	You have a account login here? <a href="index.php"><p class="text-info">Login Account</p></a>		
	</div>
	</div>
				
	<input type="hidden" <?php $_GET["token"]; ?> id="txt_token"/>
					
</form>

ajax code

Before you close the < /html > tag on the "reset_password.php" page, the jQuery / Javascript code begins.


If the alert() method does not trigger any error messages, then this code sends the user request to the "update_password.php" page via the $.ajax() method to enter a new password and hidden tag token values.


If the password update task is completed on the "update_password.php" page, the active modified password message will be shown under "#msg" div.


<script type="text/javascript">	
$(document).ready(function(){
	$(document).on("click", "#btn_update", function(e){	
					
		var password = $("#txt_password").val();
		var cpassword = $("#txt_cpassword").val();
		var token = $("#txt_token").val();
	
		if(password == ""){
			alert("Please Enter New Password ! "); 
		}
		else if(password.length < 6){
			alert("Please Enter New Password Must Six Character ! "); 
		}
		else if(cpassword == ""){
			alert("Please Enter Confirm Password !"); 
		}
		else if(password != cpassword){
			alert("Password Not Match ! "); 
		}
		else{
			$.ajax({
				url: "update_password.php",
				method: "post",
				data: {upassword:password, ucpassword:cpassword, utoken:token},
				success: function(response){
					$("#msg").html(response);
				}
			});	
		}	
	});		
});
</script>

update_password.php

This file communicates through the $.ajax() method and is responsible for silently updating the password on the back-end side with PHP PDO code and successfully transmitting the updated message.


<?php
session_start();
require_once "dbconfig.php";

// Get user enter a new password, confirm password and a token value via $.ajax() method
if(isset($_POST["upassword"]) && isset($_POST["ucpassword"]) && isset($_POST["utoken"]))	
{
	$password 	= strip_tags($_POST["upassword"]);	
	$cpassword 	= strip_tags($_POST["ucpassword"]);
	$token 		= strip_tags($_POST["utoken"]);
			
	// New password and confirm password value encrypting using password_hash() function
	$new_password	= password_hash($password, PASSWORD_DEFAULT);
	$new_cpassword	= password_hash($cpassword, PASSWORD_DEFAULT);
			
	// Apply SQL update query and updating new password 
	$update_stmt=$db->prepare("UPDATE user SET password=:pwd, cpassword=:cpwd WHERE token=:token"); 
			
	// If query properly executed, then password updated successfully in the table  
	if($update_stmt->execute(array(	":pwd"	=>$new_password, 
									":cpwd"	=>$new_cpassword, 
									":token"=>$token))){
													
		// Using session method send password updated successfully message to reset_password.php page  
		$_SESSION["updateMsg"]="Password Updated Successfully.... Please Login";
		header("location:reset_password.php");	
	}			
}
?>

Frequently Asked Questions

What is Reset Password or Forgot Password?


Reset password is the act of denying the existing password on our website for an account again and generating a new password.


Currently, most websites worldwide use email and smartphone OTP (One-Time PIN) to reset the user's password.


They send the forgotten password link inside the email to their registered email address to reset their password.


OR they send an OTP code to their mobile number registered with them. And scans whether or not user-entered OTP code validates, if yes, the user redirects to a new password formation, and the system updates it.


The OTP pin is 6 digit number usually valid for just one login session and only a few times. Smartphones such as Android, laptops, and other login gadgets are used by some people.


What's the difference between changing a password and resetting a password?


Reset Password | Forgot Password


1. Reset Password enables the user to reset the password (set a new password) without having an old password.


2. With Active Account Default Permissions, passwords can only be changed by Administrators and Account Users.


3. If you are doing an administrative action when you reset a password, you force the password to change without knowing the old password.


4. After a password has been reset, the website system updates the password under the user account.


Changing Password


1. Changing a password did require an old password from the user to set a new password.


2. The Change Password agreement allows users who alter the password to change the password. You can modify your password with active account Default Permissions.


3. You provide the old password along with the new password when you change a password. If the old password is correct and the new password meets the security policies, the password will be updated.


Download Codes

No comments:

Post a Comment

Post Bottom Ad