Skip to main content
php change password script

Change Password Code In PHP

Hello friends, I am back with another new tutorial for you. Today we will learn you about how to make a change password code in php. Do you think it is very hard? No, its just simple. You have seen in many application about change password functionality. This functionality is very useful while user forgot its password or want to change its current password. So i will not waste your time and go to the point. Let’s start…

Important for you: Email verification script using PHP and MySQL

Important for you: login logout using session in PHP example

Here we assume that we have one record in the database i.e. Email: test@test.com, Password: abcd. Here password is stored in DB with password_hash() algorithm. Password_hash algorithm is consider as one of the best secure encryption algorithm. Remember that don’t use md5() encryption. md5() encryption is now not considered as a safest encryption.You can learn more about password_hash() and password_verify() from its official site.

What logic should be used?

Here we will use simple logic for change password code in PHP. In change password form, user will fill the information like old password, new password and confirm password. We will create a old password using password_verify function and match it with all email and password in database entries. Here you should remember that you have to store user’s email or userid in the session and use it for find out user who want to change its password. If we found any matched record then it will update their new password with password_hash encryption. We are not using email in this script but you can store it in session when user login and use it whenever needs.

Now see the below practical code. So you can understand more.

Create a change password html form with Javascript validation. Here is mine code. Please don’t copy it directly. First understand it and then practice it. If you have any problem while practice it then let me know in the comment box. I will help you to solve that problem.

style.css

.form-table
{
	width:350px;
	margin-left: auto;
	margin-right: auto;
}

label{
	font-weight: bold;
}

#form_submission_ajax{
	background-color: #eee;
	padding-top: 10px;
	padding-bottom: 10px;
}

.error{
	color: #ff0000;
}

input {
    border: 2px solid #531EBF;
    padding: 4px;
}

input[type="submit"] {
    padding: 5px 15px;
    background-color: #531EBF;
    border: 2px solid #531EBF;
    color: #fff;
    border-radius: 5px;
}

h1 {
    color: #531EBF;
}

index.php

<!DOCTYPE html>
<html>
<head>
	<title>Change password in php</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.11.1.js"></script>
</head>
<body>

<?php 
session_start();
	
$error = [
"old_password_error" => '',
"new_password_error" => '',
"confirm_password_error" => ''
];

$form_data = [
"old_password" => '',
"new_password" => '',
"confirm_password" => ''
];

if(!empty($_SESSION['error']))
{
	$error = $_SESSION['error'];
}

if(!empty($_SESSION['form_data']))
{
	$form_data = $_SESSION['form_data'];
}

?>

	<h1><center>Change Password Form</center></h1>
	<form action="change-password.php" method="post" onsubmit="return validate();" id="form_submission_ajax">
		<table class="form-table">
			
			<tr>
				<td><label>Old password:</label></td>
				<td><input type="password" name="old_password" id="old_password" value="<?php echo $form_data['old_password']; ?>"></td>
			</tr>
			<tr>
				<td></td>
				<td id="old_password_error" class="error"><?php echo $error['old_password_error']; ?></td>
			</tr>

			<tr>
				<td><label>New Password:</label></td>
				<td><input type="password" name="new_password" id="new_password" value="<?php echo $form_data['new_password']; ?>"></td>
			</tr>
			<tr>
				<td></td>
				<td id="new_password_error" class="error"><?php echo $error['new_password_error']; ?></td>
			</tr>

			<tr>
				<td><label>Confirm Password:</label></td>
				<td><input type="password" name="confirm_password" id="confirm_password" value="<?php echo $form_data['confirm_password']; ?>"></td>
			</tr>

			<tr>
				<td></td>
				<td id="confirm_password_error" class="error"><?php echo $error['confirm_password_error']; ?></td>
			</tr>

			<tr>
				<td></td>
				<td>
					<input type="hidden" name="user_id" id="user_id" value="1">
					<input type="submit" name="submit" value="Submit">
				</td>
			</tr>
		</table>
	</form>
</body>

<script type="text/javascript">
function validate()
{
	var valid = true;
	var old_password = $('#old_password').val();
	var new_password = $('#new_password').val();
	var confirm_password = $('#confirm_password').val();

	if(old_password=='' || old_password==null)
	{
		valid=false;
		$('#old_password_error').html("* This field is required.");
	}
	else
	{
		$('#old_password_error').html("");	
	}

	if(new_password=='' || new_password==null)
	{
		valid=false;
		$('#new_password_error').html("* This field is required.");
	}
	else
	{
		$('#new_password_error').html("");
	}

	if(confirm_password=='' || confirm_password==null)
	{
		valid=false;
		$('#confirm_password_error').html("* This field is required.");
	}
	else
	{
		$('#confirm_password_error').html("");
	}

	if(new_password != '' && confirm_password != '')
	{
		if(new_password != confirm_password)
		{
			valid = false;
			$('#confirm_password_error').html("* Confirm password is same as new password.");
		}

		if(new_password == confirm_password)
		{
			$('#confirm_password_error').html("");			
		}
	}

	if(valid==true)
	{
		return true;
	}
	else
	{
		return false;
	}
}
</script>
</html>	

<?php 
$_SESSION['error'] = "";
$_SESSION['form_data'] = "";
?>

In the above form, there are three fields named old password, new password and confirm password. New password and current password will same. This form will validate using javascript before submit. So if user does not type confirm password same as new password then error established. Try that one 😉

Now here is a code for change a password using PHP on the server. We have also validate form data on the server side.

change-password.php

<?php 
session_start();
$email = "test@test.com";
$valid = true;
$error = [];
$form_data = [];

if(!empty($_POST['old_password']))
{
	$old_password = $_POST['old_password'];
	$old_password_data = array("old_password" => $old_password);
	$form_data = array_merge($form_data, $old_password_data);
	$old_password_error = array("old_password_error" => "");
	$error = array_merge($error, $old_password_error);
}
else
{
	$valid = false;
	$old_password = "";
	$old_password_data = array("old_password" => $old_password);
	$form_data = array_merge($form_data, $old_password_data);
	$old_password_error = array("old_password_error" => "* Old password is required.");
	$error = array_merge($error, $old_password_error);
}

if(!empty($_POST['new_password']))
{
	$new_password = $_POST['new_password'];
	$new_password_data = array("new_password" => $new_password);
	$form_data = array_merge($form_data, $new_password_data);
	$new_password_error = array("new_password_error" => "");
	$error = array_merge($error, $new_password_error);
}
else
{
	$valid = false;
	$new_password = "";
	$new_password_data = array("new_password" => $new_password);
	$form_data = array_merge($form_data, $new_password_data);
	$new_password_error = array("new_password_error" => "* New password is required.");
	$error = array_merge($error, $new_password_error);
}

if(!empty($_POST['confirm_password']))
{
	$confirm_password = $_POST['confirm_password'];
	$confirm_password_data = array("confirm_password" => $confirm_password);
	$form_data = array_merge($form_data, $confirm_password_data);
	$confirm_password_error = array("confirm_password_error" => "");
	$error = array_merge($error, $confirm_password_error);
}
else
{
	$valid = false;
	$confirm_password = "";
	$confirm_password_data = array("confirm_password" => $confirm_password);
	$form_data = array_merge($form_data, $confirm_password_data);
	$confirm_password_error = array("confirm_password_error" => "* Confirm password is required.");
	$error = array_merge($error, $confirm_password_error);
}

if($new_password != '' && $confirm_password != '')
{
	if($new_password != $confirm_password)
	{
		$valid = false;
		$confirm_password_error = array("confirm_password_error" => "* Confirm password is same as new password.");
		$error = array_merge($error, $confirm_password_error);
	}

	if($new_password == $confirm_password)
	{
		$confirm_password_error = array("confirm_password_error" => "");
		$error = array_merge($error, $confirm_password_error);
	}
}

if($valid==true)
{
	include 'config.php';
	mysqli_select_db($conn, $db_name);
	$check_data = "SELECT * FROM user_login WHERE email = '$email' ";
	$check_query = mysqli_query($conn, $check_data);
	$numRows = mysqli_num_rows($check_query);
	$user_data = mysqli_fetch_assoc($check_query);

	if($numRows == 1)
	{
		$check_old_password = password_verify($old_password,$user_data['password']);
		if($check_old_password)
		{
			$new_password_encrypt = password_hash($new_password,PASSWORD_DEFAULT);
			$user_id = $user_data['id'];
			$sql = "UPDATE user_login SET password = '$new_password_encrypt' WHERE id = '$user_id' ";
			$query = mysqli_query($conn, $sql);
			$row = mysqli_affected_rows($query);
			if($row == 1)
			{
				echo "Your password successfully changed.";
				die;
			}
		}
		else
		{
			echo "Opps, We can not find your data. Please try again.";
			die;
		}
	}
	else
	{
		echo "No database record matched with your data.";
		die;
	}
}
else
{
	$_SESSION['error'] = $error;
	$_SESSION['form_data'] = $form_data;
	header('Location:index.php');
}
?>

All the data filled by user are on the server now. It’s time to validate them using php validation.
In the change password script we use server side validation using PHP. If form data does not satisfy the validation condition then script will redirect to “index.php” with errors. Otherwise password will change in the database.

I hope that you like this tutorial. Please share it with your friends. If you have any kind of problem regarding this tutorial then let me know in the comment box. I will help you to solve the problem. Thank you 🙂

admin

HI, i am software developer having knowledge of PHP, C, C++ programming languages. I am very passionate about programming and ability to solve the programming problems. CodeandTuts is my blog where i like to put new tutorial and help new developer.

One thought on “Change Password Code In PHP

Leave a Reply

Your email address will not be published. Required fields are marked *