How to Maintain Password History Using PHP and Mysql

In this article, you will learn How to Maintain Password History Using PHP and Mysql. In this user change their password can’t reuse. New Password should not be the same as any of the previous 3 Passwords.

In this tutorial having three pages

  • db.php
  • index.php
  • change_password.php

db.php

<?php 
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','pwdhistory');
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>

index.php

<?php
session_start();
error_reporting(0);
include('db.php');
if(isset($_POST['submit']))
  {
$fullname=$_POST['fname'];
$email=$_POST['email'];
$password=md5($_POST['password']);
// Code for check email availability
$rt="SELECT * from registration where email=:email";
$query2= $dbh -> prepare($rt);
$query2->bindParam(':email', $email, PDO::PARAM_STR);
$query2-> execute();
$results = $query2->fetchAll(PDO::FETCH_OBJ);
if($query2->rowCount() > 0)
{
$error="Email id already registered ";
}
else{
$sql="INSERT INTO  registration(FullName,email,Password) VALUES(:fullname,:email,:password)";
$query = $dbh->prepare($sql);
$query->bindParam(':fullname',$fullname,PDO::PARAM_STR);
$query->bindParam(':email',$email,PDO::PARAM_STR);
$query->bindParam(':password',$password,PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if($lastInsertId)
{
$ret="INSERT INTO password_history(useremail,password) VALUES(:email,:password)";
$query1 = $dbh->prepare($ret);
$query1->bindParam(':email',$email,PDO::PARAM_STR);
$query1->bindParam(':password',$password,PDO::PARAM_STR);
$query1->execute();	
$msg="Your info submitted successfully";
}
else 
{
$error="Something went wrong. Please try again";
}
}
}
// code for login
if(isset($_POST['login']))
{
$email=$_POST['emailid'];
$password=md5($_POST['password']);
$sql ="SELECT email,Password,FullName FROM registration WHERE email=:email and Password=:password";
$query= $dbh -> prepare($sql);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':password', $password, PDO::PARAM_STR);
$query-> execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach ($results as $result) {
$_SESSION['fname']=$result->FullName;
$_SESSION['login']=$_POST['emailid'];
echo "<script type='text/javascript'> document.location ='change_password.php'; </script>";
}
} 
else{
echo "<script>alert('Invalid Details');</script>";
}
}
?>
<html>
<head>
		<title>Register and Login</title>
		<style>
		li{
		list-style:none;
		}
		h1{
		text-align:center;
		}
		</style>
</head>
<body>
	<div class="main">
		<div class="header" >
			<h1>Login or Create a Free Account!</h1>
		</div>
			<form method="post">
				<ul class="left-form">
					<h2>Create Account</h2>
					<li>
						<input type="text"   placeholder="Full Name" name="fname" id="fname" required/>
					
						<div class="clear"> </div>
					</li> 
					<li>
						<input type="email"   placeholder="Email" name="email" id="email" required/>
						
						<div class="clear"> </div>
					</li> 
					<li>
						<input type="password"  name="password" id="password" placeholder="password" autocomplete="off" required/>
					
						<div class="clear"> </div>
					</li> 
					
				
					<input type="submit" name="submit" value="Create Account">
						<div class="clear"> </div>
				</ul>
				</form>

				<form method="post">
				<ul class="right-form">
					<h3>Login</h3>
					<div>
						<li><input type="text"  placeholder="Reg Email" name="emailid" autocomplete="off" required/></li>
						<li> <input type="password"  placeholder="Password" name="password" required/></li>
							<h4>I forgot my Password!</h4>
							<input type="submit" name="login" value="Login" >
					</div>
					<div class="clear"> </div>
				</ul>
				<div class="clear"> </div>
					
			</form>
			
		</div>


	
</body>
</html>

change_password.php

<?php
session_start();
error_reporting(0);
include('db.php');
if(strlen($_SESSION['login'])==0)
    {   
    header("Location: index.php"); 
    }
    else{
// full Code for change password

if(isset($_POST['change']))   	
{
$email=$_SESSION['login'];
$oldpass=md5($_POST['oldpass']);
 $newpass=md5($_POST['newpass']);
 // Code for vefify current Password
 $query2 = $dbh->prepare("SELECT Password FROM  registration WHERE email =:email and Password=:oldpass");
$query2->bindParam(':email', $email, PDO::PARAM_STR);
$query2->bindParam(':oldpass', $oldpass, PDO::PARAM_STR);
$query2-> execute();
$results = $query2->fetchAll(PDO::FETCH_OBJ);
if($query2->rowCount() > 0)
{
$query=$dbh->prepare("SELECT * FROM password_history WHERE useremail=:email order by id desc limit 3");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query-> execute();
$resultss = $query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
$passwrd=array();
foreach($resultss as $rt)
{
array_push($passwrd,$rt->password);
}

if(in_array($newpass,$passwrd))
{
    
$error="Your new Password should not be same as any of the previous 3 Passwords";

}

else {
$con="update registration set Password=:cmppass where email=:email";
$chngpwd1 = $dbh->prepare($con);
$chngpwd1->bindParam(':cmppass', $newpass, PDO::PARAM_STR);
$chngpwd1->bindParam(':email', $email, PDO::PARAM_STR);
$chngpwd1->execute();
//Code for insertion new password in tblpassword history 
$sql="INSERT INTO password_history(useremail,password) VALUES(:email,:newpassrd)";
$query = $dbh->prepare($sql);
$query->bindParam(':email',$email,PDO::PARAM_STR);
$query->bindParam(':newpassrd',$newpass,PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if($lastInsertId)
{
$msg="Password changed successfully ";
}
}
}
else{
$error="Current password not matched ";
}   
}
?>
<html>
<head>
		<style>
    li{
	list-style:none;
	}
</style>
<script type="text/javascript">
function valid()
{
if(document.chngpwd.newpass.value!= document.chngpwd.confirmpassword.value)
{
alert("New Password and Confirm Password Field do not match  !!");
document.chngpwd.newpass.focus();
return false;
}
return true;
}
</script>
</head>
<body>
	<div class="main">
		
			<form   name="chngpwd" method="post" onSubmit="return valid();">
				<ul class="left-form">
					<h2>Change Password</h2>
 
					<li>
						<input type="password"   placeholder="Current Password" name="oldpass" id="oldpass" autocomplete="off" required/>
					
						<div class="clear"> </div>
					</li> 
					<li>
						<input type="password"   placeholder="New Password" name="newpass" id="newpass" autocomplete="off" required/>
						
						<div class="clear"> </div>
					</li> 
					<li>
						<input type="password"  name="confirmpassword" id="confirmpassword" placeholder="Confirm Password" autocomplete="off" required/>
					
						<div class="clear"> </div>
					</li> 
					
				
					<input type="submit" name="change" value="Change">
						<div class="clear"> </div>
				</ul>
				</form>
				<div class="clear"> </div>
		</div>


	
</body>
</html>

25 thoughts on “How to Maintain Password History Using PHP and Mysql”

  1. Whats up are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do
    you require any coding expertise to make your own blog?
    Any help would be really appreciated!

    Reply
  2. Simply wish to say your article is as astonishing. The clarity in your post is just excellent and i can assume you are an expert
    on this subject. Well with your permission allow me
    to grab your feed to keep updated with forthcoming
    post. Thanks a million and please continue the enjoyable work.

    Reply
  3. I’d like to thank you for the efforts you have put in writing this site.
    I am hoping to view the same high-grade blog posts from you in the future as
    well. In truth, your creative writing abilities has motivated me to get
    my own, personal blog now 😉

    Reply
  4. This is really interesting, You’re a very skilled blogger.
    I have joined your rss feed and look forward to seeking more of your wonderful
    post. Also, I’ve shared your site in my social networks!

    Reply
  5. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your
    blog? My blog is in the exact same niche as yours and my users would certainly benefit from a lot of the information you provide here.

    Please let me know if this okay with you. Appreciate it!

    Reply
  6. I was suggested this web site by my cousin. I am not certain whether this post is
    written by way of him as nobody else recognise such certain approximately my trouble.

    You’re incredible! Thank you!

    Reply
  7. Excellent post. I was checking continuously this blog and I’m inspired!

    Extremely helpful information specifically the
    closing phase 🙂 I maintain such info much. I used to be looking
    for this certain info for a very long time. Thank you and good luck.

    Reply
  8. Generally I don’t read post on blogs, but I would like to say that this write-up very pressured me to try and do so!
    Your writing taste has been amazed me. Thank you, quite great post.

    Reply

Leave a Comment