Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
PHP
<?php 
	include('functions.php');

	if (!isLoggedIn()) {
		$_SESSION['msg'] = "You must log in first";
		header('location: login.php');
	}
	if (isset($_GET['edit'])) {
		$id = $_GET['edit'];
		$update = true;
		$record = mysqli_query($db, "SELECT * FROM users WHERE id=$id");

		if (count(array($record)) == 1 ) {
			$n = mysqli_fetch_array($record);
		
			$id 		 =	$n['id'];
			$username    =  $n['username'];
			$email       =  $n['email'];
			$user_type	 = 	$n['user_type'];
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<div class="header">
		<h2>Home Page</h2>
	</div>
	<div class="content">
		<!-- notification message -->
		<?php if (isset($_SESSION['success'])) : ?>
			<div class="error success" >
				<h3>
					<?php 
						echo $_SESSION['success']; 
						unset($_SESSION['success']);
					?>
				</h3>
			</div>
		<?php endif ?>
		<!-- logged in user information -->
		<div class="profile_info">
			<img src="images/user_profile.png"  >

			<div>
				<?php  if (isset($_SESSION['user'])) : ?>
					<strong><?php echo $_SESSION['user']['username']; ?></strong>
<?php echo $_SESSION ['user']['id']; ?><br>
<?php echo $_SESSION ['user']['email']; ?><br>

					<small>
						<i  style="color: #888;">(<?php echo ucfirst($_SESSION['user']['user_type']); ?>)</i> 
						<br>
						<a href="index.php?logout='1'" style="color: red;">logout</a>
						<a href="userlists.php">profiel setting</a>
						<a href="pass.php">changepass</a>
												
					</small>

				<?php endif ?>
			</div>
		</div>
	</div>
</body>
</html>

<?php 
	session_start();

	// connect to database
	$db = mysqli_connect('localhost', 'root', '', 'multi_login');

	// variable declaration
	$username = "";
	$user_type="";
	$email    = "";
	$password ="";
	$id = 0;
	$update = false;
	$errors   = array(); 

	// call the register() function if register_btn is clicked
	if (isset($_POST['register_btn'])) {
		register();
	}

	// call the login() function if register_btn is clicked
	if (isset($_POST['login_btn'])) {
		login();
	}

	if (isset($_GET['logout'])) {
		session_destroy();
		unset($_SESSION['user']);
		unset($_SESSION['cashier']);
		header("location: ../login.php");
	}

	// REGISTER USER
	function register(){
		global $db, $errors;

		// receive all input values from the form
		$username    =  e($_POST['username']);
		$email       =  e($_POST['email']);
		$password_1  =  e($_POST['password_1']);
		$password_2  =  e($_POST['password_2']);

		// form validation: ensure that the form is correctly filled
		if (empty($username)) { 
			array_push($errors, "Username is required"); 
		}
		if (empty($email)) { 
			array_push($errors, "Email is required"); 
		}
		if (empty($password_1)) { 
			array_push($errors, "Password is required"); 
		}
		if ($password_1 != $password_2) {
			array_push($errors, "The two passwords do not match");
		}

		// register user if there are no errors in the form
		if (count($errors) == 0) {
			$password = md5($password_1);//encrypt the password before saving in the database

			if (isset($_POST['user_type'])) {
				$user_type = e($_POST['user_type']);
				$query = "INSERT INTO users (username, email, user_type, password) 
						  VALUES('$username', '$email', '$user_type', '$password')";
				mysqli_query($db, $query);
				$_SESSION['success']  = "Password successfully changed!!";
				header('location: home.php');
			}			
			else{
				$query = "INSERT INTO users (username, email, user_type, password) 
						  VALUES('$username', '$email', 'user', '$password')";
				mysqli_query($db, $query);

				// get id of the created user
				$logged_in_user_id = mysqli_insert_id($db);

				$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
				$_SESSION['cashier'] = getUserById($logged_in_user_id); // put logged in user in session
				$_SESSION['success']  = "You are now logged in";
				header('location: index.php');				
			}
		}
	}
	
	

	
	//display in all user list 
	$results = mysqli_query($db,"SELECT * FROM users  LIMIT 1");

	
	
	
	// call the editer() function if register_btn is clicked
	if (isset($_POST['editer_btn'])) {
		editer();
	}

	

	// Edit USER
	function editer(){
		global $db, $errors;

		// receive all input values from the form
		$id 		 =	e($_POST['id']);
		$username    =  e($_POST['username']);
		$email       =  e($_POST['email']);
		$user_type = e($_POST['user_type']);
		

		// form validation: ensure that the form is correctly filled
		if (empty($username)) { 
			array_push($errors, "Username is required"); 
		}
		if (empty($email)) { 
			array_push($errors, "Email is required"); 
		}
		if (empty($user_type)) { 
			array_push($errors, "User Tpye is required"); 
		}
		

		// register user if there are no errors in the form
		if (count($errors) == 0) {
			$user_type = e($_POST['user_type']);
			if (isset($_POST['editer_btn'])) {
				
				$query = "UPDATE users SET username='$username',email='$email', user_type='$user_type' WHERE id=$id";
				mysqli_query($db, $query);
				$_SESSION['success']  = "modified user successfully created!!";
				header('location: listuser.php');
			}
			
			
}
			
			else{

		}
		
	}

	// call the change_pass() function if register_btn is clicked
	if (isset($_POST['change_pass_btn'])) {
		change_password();
	}
	
	
	// CHANGE USER PASSWORD
	function change_password(){
		global $db, $errors;

		// receive all input values from the form
		$id 		 =	e($_POST['id']);
		$username    =  e($_POST['username']);
		$password_1  =  e($_POST['password_1']);
		$password_2  =  e($_POST['password_2']);

		// form validation: ensure that the form is correctly filled
		if (empty($username)) { 
			array_push($errors, "Username is required"); 
		}
		
		if (empty($password_1)) { 
			array_push($errors, "Password is required"); 
		}
		if ($password_1 != $password_2) {
			array_push($errors, "The two passwords do not match");
		}

		// change user password if there are no errors in the form
		if (count($errors) == 0) {
			$password = md5($password_1);//encrypt the password before saving in the database

			if (isset($_POST['change_pass_btn'])) {
				$user_type = e($_POST['user_type']);
				$query = "UPDATE users SET username='$username',password='$password' WHERE id=$id";
				mysqli_query($db, $query);
				$_SESSION['success']  = "user password  successfully changed!!";
				header('location: home.php');
			}
			
			

			else  {
							
			}
		}
		
		
		

		// change profile user password if there are no errors in the form
		if (count($errors) == 0) {
			$password = md5($password_1);//encrypt the password before saving in the database

			if (isset($_POST['change_pass_btn'])) {
				
				$user_type = e($_POST['user_type']);
				$query = "UPDATE users SET username='$username',password='$password' WHERE id=$id";
				mysqli_query($db, $query);
				$_SESSION['success']  = "user password  successfully changed!!";
				header('location: index.php');
			}
			
			

			else{
							
			}
		}
	}

	
	
	
	
	
	
	// return user array from their id
	function getUserById($id){
		global $db;
		$query = "SELECT * FROM users WHERE id=" . $id;
		$result = mysqli_query($db, $query);

		$user = mysqli_fetch_assoc($result);
		return $user;
	}
	
	
	

	// LOGIN USER
	function login(){
		global $db, $username, $errors;

		// grap form values
		$username = e($_POST['username']);
		$password = e($_POST['password']);

		// make sure form is filled properly
		if (empty($username)) {
			array_push($errors, "Username is required");
		}
		if (empty($password)) {
			array_push($errors, "Password is required");
		}

		// attempt login if no errors on form
		if (count($errors) == 0) {
			$password = md5($password);

			$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
			$results = mysqli_query($db, $query);

			if (mysqli_num_rows($results) == 1) { // user found
				// check if user is admin or user
				$logged_in_user = mysqli_fetch_assoc($results);
				if ($logged_in_user['user_type'] == 'admin') {

					$_SESSION['user'] = $logged_in_user;
					$_SESSION['success']  = "You are now logged in";
					header('location: admin/home.php');		  
				}
				else if ($logged_in_user['user_type'] == 'user'){
					$_SESSION['user'] = $logged_in_user;
					$_SESSION['success']  = "You are now logged in";

					header('location: index.php');
					
					
				}
				
				else if ($logged_in_user['user_type'] == 'cashier'){
					$_SESSION['cashier'] = $logged_in_user;
					$_SESSION['success']  = "You are now logged in";

					header('location: index1.php');
					
					
				}
				
				
			}else {
				array_push($errors, "Wrong username/password combination");
			}
		}
	}

	function isLoggedIn()
	{
		if (isset($_SESSION['user'])) {
			return true;
		}else{
			return false;
		}
	}

function isCashierIn()
	{
		if (isset($_SESSION['cashier'])) {
			return true;
		}else{
			return false;
		}
	}

	function isAdmin()
	{
		if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
			return true;
		}else{
			return false;
		}
	}
	
	

	// escape string
	function e($val){
		global $db;
		return mysqli_real_escape_string($db, trim($val));
	}

	function display_error() {
		global $errors;

		if (count($errors) > 0){
			echo '<div class="error">';
				foreach ($errors as $error){
					echo $error .'<br>';
				}
			echo '</div>';
		}
	}

?>

<?php
session_start();
$id =  $_SESSION ['user']['id'];/* userid of the user */
$con = mysqli_connect('localhost','root','','multi_login') or die('Unable To connect');
if(count($_POST)>0) {
$result = mysqli_query($con,"SELECT *from users WHERE id='" . $id . "'");
$row=mysqli_fetch_array($result);
if ($_POST["currentPassword"] == $row["password"] && ($_POST["newPassword"]) == $row["confirmPassword"] ) {
mysqli_query($con,"UPDATE users set password= '" . md5($_POST["newPassword"]) . "' WHERE id='" . $id . "'");
$message = "Password Changed Sucessfully";
} else{
 $message = "Password is not correct";
}
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Password Change</title>

</head>
<body>
<h3 align="center">CHANGE PASSWORD</h3>
<div><?php if(isset($message)) { echo $message; } ?></div>
<form method="post" action="" align="center">
Current Password:<br>
<input type="password" name="currentPassword"><span id="currentPassword" class="required"></span>
<br>
New Password:<br>
<input type="password" name="newPassword"><span id="newPassword" class="required"></span>
<br>
Confirm Password:<br>
<input type="password" name="confirmPassword"><span id="confirmPassword" class="required"></span>
<br><br>
<input type="submit" name="submit">
</form>
<br>=
<br>
</body>
</html>


What I have tried:

<?php
session_start();
$id =  $_SESSION ['user']['id'];/* userid of the user */
$con = mysqli_connect('localhost','root','','multi_login') or die('Unable To connect');
if(count($_POST)>0) {
$result = mysqli_query($con,"SELECT *from users WHERE id='" . $id . "'");
$row=mysqli_fetch_array($result);
if ($_POST["currentPassword"] == $row["password"] && ($_POST["newPassword"]) == $row["confirmPassword"] ) {
mysqli_query($con,"UPDATE users set password= '" . md5($_POST["newPassword"]) . "' WHERE id='" . $id . "'");
$message = "Password Changed Sucessfully";
} else{
 $message = "Password is not correct";
}
}

?>
Posted
Updated 16-Jun-20 2:52am
v2

1 solution

Not a solution to your problem, but major design flaws in that code ...

Firstly, MD5 is not encryption: it's hashing. They are very different things. And this code:
PHP
$password = md5($password_1);//encrypt the password before saving in the database
Is very poor from a security point of view. You need to salt the password, preferably using something specific to the user like a Uuse ID to prevent identical passwords getting identical hashes. Without it, everyone who has the password "password" (and that's much, much more common than you think) has an identical hash, and that's one of the things hacks will look for. Common hash, common password - so it's probably one of teh really obvious ones ... and they are in with no effort.

Secondly, never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
Richard Deeming 16-Jun-20 9:21am    
Hey, it's not like PHP has built-in functions for handling passwords or anything! :)

PHP: password_hash[^]
PHP: password_verify[^]
Member 13751016 21-Jun-20 13:07pm    
but where i correction? please help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900