Skip to main content

Build Password Reset System with PHP & MySQL

Password reset is a common feature web applications to allow users to reset their password if users forget their password. The password reset is allowed with username or email address to send password reset link to users email id to save their new password.

So if you’re thinking about implementing password reset with PHP in your application, then you’re here at right place. In this tutorial you will learn how to implement password reset or forget password functionality using PHP and MySQL. You can also develop complete User Management System with PHP & MySQL to manage users.

We will cover this tutorial step by step with live demo. You will also be able to download complete source code of live demo.

Also, read:

  • config.php
  • index.php
  • forget_password.php
  • reset_password.php
  • user.js
  • action.php
  • User.php
  • Step1: Create MySQL Database Table

    In this tutorial, we will create live example for password reset functionality. So we will create MySQL database table members for user login details.

    CREATE TABLE `members` (
      `id` int(11) NOT NULL,
      `username` varchar(250) NOT NULL,
      `email` varchar(250) NOT NULL,
      `password` varchar(250) NOT NULL,
      `authtoken` varchar(250) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    We will insert user records into members table for password reset functionality.

    INSERT INTO `members` (`id`, `username`, `email`, `password`, `authtoken`) VALUES
    (1, 'test', 'test@webdamn.com', '827ccb0eea8a706c4c34a16891f84e7b', '91e8cc3c6bc400c70fd17c3836e01287');
    

    Step2: Create User Login Form

    First we will create user login form in index.php with forget password link.

    <div class="container login-container">
    	<div class="row">                
    		<div class="col-md-6 login-form-2">
    			<h3>User Login</h3>
    			<form id="loginForm" method="POST">
    				<div id="errorMessge" class="alert alert-danger hidden">                            
    				</div>
    				<div class="form-group">
    					<input type="text" name="userEmail" class="form-control" placeholder="Email..." required />
    				</div>
    				<div class="form-group">
    					<input type="password" name="userPassword"  class="form-control" placeholder="Password..." required />
    				</div>
    				<div class="form-group">
    					<input type="hidden" name="action"  value="login" />
    					<input type="submit" class="btnSubmit" value="Login" />
    				</div>
    				<div class="form-group">
    					<a href="forget_password.php" class="ForgetPwd">Forget Password?</a>
    				</div>
    			</form>
    		</div>
    	</div>
    </div>		
    

    Step3: Implement User Login

    We will implement user login functionality by handling user login form submit in user.js. We will make ajax request to action.php to handle user login and get JSON response.

    $('#loginForm').on('submit', function(e){
    	$.ajax({
    		type: 'POST',			
    		url : "action.php",						
    		data: $(this).serialize(),
    		dataType: "json",
    		success: function (response) {
    			if(response.success == 1) {	
    				location.href = "index.php";
    			} else {
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden');
    			}				
    		}
    	});
    	return false;
    });
    

    In action.php, we will call method $user->login() to implement user login functionality.

    <?php
    include("inc/User.php"); 
    $user = new User();
    if(!empty($_POST['action']) && $_POST['action'] == 'login') {
    	$userDetails = $user->login();
    	if($userDetails){		
    		$message = "Logged in successfully";
    		$status = 1;
    	} else {
    		$message = "Invalid Email/Password";
    		$status = 0;
    	}
    	$jsonResponse = array (
    		"message"	=> $message,
    		"success" => $status	
    	);
    	echo json_encode($jsonResponse);	
    }
    ?>
    

    In class User.php, we will define method login().

    public function login(){
    	$sqlQuery = "
    		SELECT * 
    		FROM ".$this->memberTable." 
    		WHERE email='".$_POST['userEmail']."' AND password='".md5($_POST['userPassword'])."'";			
    	return  $this->getData($sqlQuery);
    }
    

    Step4: Create Forget Password Form

    If user forget password, then user can reset their password by clicking Forget Password link on login form. The forget password form created in forget_password.php to reset form using username or email address.

    <div class="container login-container">
    	<div class="row">                
    		<div class="col-md-6 login-form-2">
    			<h3>Forget Password Form</h3>						
    			<form id="forgetForm" method="POST">
    				<div id="errorMessge" class="alert hidden">                            
    				</div>
    				<div id="inputSection">
    					<div class="form-group">
    						<input type="text" name="userName" class="form-control" placeholder="Username..." />
    					</div>
    					<div class="form-group">
    						OR
    					</div>						
    					<div class="form-group">
    						<input type="email" name="userEmail" class="form-control" placeholder="Email address..." />
    					</div>
    					<div class="form-group">
    						<input type="hidden" name="action"  value="forgetPassword" />
    						<input type="submit" class="btnSubmit" value="Reset Password" />
    					</div> 
    				</div>						
    			</form>
    		</div>
    	</div>
    </div>
    

    Step5: Implement Password Reset Functionality

    Now we will implement password reset functionality by making ajax request to action.php.

    $('#forgetForm').on('submit', function(e){		
    	$.ajax({
    		type: 'POST',			
    		url : "action.php",						
    		data: $(this).serialize(),
    		dataType: "json",
    		success: function (response) {				
    			if(response.success == 2) {	
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden alert-success').addClass('alert-danger');
    			} else if(response.success == 1) {
    				$('#inputSection').addClass('hidden');
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden alert-danger').addClass('alert-success');					
    			} else if(response.success == 0) {
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden alert-success').addClass('alert-danger');
    			}
    		}
    	});
    	return false;
    });
    

    In action.php, we will call method $user->resetPassword() from User.php class and return JSON response.

    if(!empty($_POST['action']) && $_POST['action'] == 'forgetPassword') {	
    	if($_POST['userEmail'] == '' && $_POST['userName'] == '') {
    		$message = "Please enter username or email to proceed with password reset";
    		$status = 2;
    	} else {
    		$userDetails = $user->resetPassword();
    		if($userDetails){		
    			$message = "Password reset link send. Please check your mailbox to reset password.";
    			$status = 1;
    		} else {
    			$message = "No account exist with entered username and email address.";
    			$status = 0;
    		}
    	}	
    	$jsonResponse = array (
    		"message"	=> $message,
    		"success" => $status	
    	);
    	echo json_encode($jsonResponse);
    }
    

    In class User.php, we will define method resetPassword(). In this method, we will check for user account by username or email. If user account exist then we will create password reset link with authtoken and send password reset email to user email address.

    public function resetPassword(){
    	$sqlQuery = "
    		SELECT email 
    		FROM ".$this->memberTable." 
    		WHERE email='".$_POST['userEmail']."' OR username='".$_POST['userName']."'";			
    	$result = mysqli_query($this->dbConnect, $sqlQuery);
    	$numRows = mysqli_num_rows($result);
    	if($numRows) {
    		while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {				
    			$link="Reset Password";				
    			$to = $row['email'];
    			$subject = "Reset your password on examplesite.com";
    			$msg = "Hi there, click on this ".$link." to reset your password.";
    			$msg = wordwrap($msg,70);
    			$headers = "From: info@webdamn.com";
    			mail($to, $subject, $msg, $headers);
    			return 1;
    		}
    	} else {
    		return 0;
    	}
    }
    

    Step6: Create Password Reset Form

    When user click password reset link, then the user password reset form displayed to save new password. So we will create new password save form in reset_password.php.

    <div class="container login-container">
    	<div class="row">                
    		<div class="col-md-6 login-form-2">
    			<h3>Reset Password Form</h3>
    			<?php if(!empty($_GET['authtoken']) && $_GET['authtoken']) { ?>
    			<form id="savePasswordForm" method="POST">
    				<div id="errorMessge" class="alert hidden">                            
    				</div>
    				<div class="form-group">
    					<input type="password" name="newPassword" class="form-control" placeholder="New Password..." required />
    				</div>
    				<div class="form-group">
    					<input type="password" name="confirmNewPassword" class="form-control" placeholder="Confirm password..." required />
    				</div>
    				<div class="form-group">
    					<input type="hidden" name="action"  value="savePassword" />
    					<input type="hidden" name="authtoken"  value="<?php echo $_GET['authtoken']; ?>" />
    					<input type="submit" class="btnSubmit" value="Save Password" />
    				</div>                       
    			</form>
    			<?php } ?>
    		</div>
    	</div>
    </div>
    

    Step7: Save New Password

    Now we will implement functionality to save new password. We will make ajax request to action.php to save password.

    $('#savePasswordForm').on('submit', function(e){		
    	$.ajax({
    		type: 'POST',			
    		url : "action.php",						
    		data: $(this).serialize(),
    		dataType: "json",
    		success: function (response) {				
    			if(response.success == 1) {					
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden alert-danger').addClass('alert-success');		
    				$('#savePasswordForm')[0].reset();
    			} else if(response.success == 0) {
    				$('#errorMessge').text(response.message);
    				$('#errorMessge').removeClass('hidden alert-success').addClass('alert-danger');
    			}
    		}
    	});
    	return false;
    });
    

    In action.php, we call method $user->savePassword() from class User.php to save new password.

    if(!empty($_POST['action']) && $_POST['action'] == 'savePassword' && $_POST['authtoken']) {	
    	if($_POST['newPassword'] != $_POST['confirmNewPassword']) {
    		$message = "Password does not match the confirm password field";
    		$status = 0;
    	} else {
    		$isPasswordSaved = $user->savePassword();
    		if($isPasswordSaved) {
    			$message = "Password saved successfully.";
    			$status = 1;
    		} else {
    			$message = "Invalid password change request.";
    			$status = 0;
    		}
    	}
    	$jsonResponse = array (
    		"message"	=> $message,
    		"success" => $status	
    	);
    	echo json_encode($jsonResponse);
    }
    

    In User.php class, we will define method savePassword() to save new password.

    public function savePassword(){
    	$sqlQuery = "
    		SELECT email, authtoken 
    		FROM ".$this->memberTable." 
    		WHERE authtoken='".$_POST['authtoken']."'";			
    	$result = mysqli_query($this->dbConnect, $sqlQuery);
    	$numRows = mysqli_num_rows($result);
    	if($numRows) {
    		while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    			$sqlQuery = "
    				UPDATE ".$this->memberTable." 
    				SET password='".md5($_POST['newPassword'])."'
    				WHERE email='".$row['email']."' AND authtoken='".$row['authtoken']."'";	
    			mysqli_query($this->dbConnect, $sqlQuery);	
    		}
    		return 1;
    	} else {
    		return 0;
    	}	
    }
    

    You may also like:

    You can view the live demo from the Demo link and can download the script from the Download link below.
    Demo Download

    6 thoughts on “Build Password Reset System with PHP & MySQL

    1. Hi team.
      Kindly I Need Assist on How to Create login system with One-Time-Password for Security to my system

    Comments are closed.