Login error : How do i login to different users i cannot seem to find a solution kindly help please?

This is my login form page.

<?php include "server.php";
include "ehsserver.php";

?>


<!doctype html>

<html>
	<head>
		<title> NEAR MISS </title>
		<link rel="stylesheet" href="styleforlogin.css">
	        <img src="title.png" style= "width:45%; margin-left:27%;margin-top:0% ">
                <a style="margin-left:22%; color:white;" href="/Admin/login.php">ADMIN</a>
	</head>
	<body>
	<div class="loginBox">
		
		<img src="user.png" class="user">
		<h2>Login</h2>
		<form action="login.php" method="POST">
			<p>Username</p>
			<input type="text" name = "username" placeholder="Enter ID">
			<p>Password</p>
			<input type="password" name = "password" placeholder="Enter Password">
			<input type="submit" name = "login_user" value="login">
            <?php include('errors.php'); ?>
			
		</form>
	</div>
	</body>
</html>

This is my server.php

<?php  
  
// Starting the session, necessary 
// for using session variables 
session_start(); 
   
// Declaring and hoisting the variables 
$username = ""; 
$email    = ""; 
$errors = array();  
$_SESSION['success'] = ""; 
   
// DBMS connection code -> hostname, 
// username, password, database name 
$db = mysqli_connect('localhost', 'root', '', 'registration'); 
   
// Registration code 
if (isset($_POST['reg_user'])) { 
   
    // Receiving the values entered and storing 
    // in the variables 
    // Data sanitization is done to prevent 
    // SQL injections 
    $username = mysqli_real_escape_string($db, $_POST['username']); 
    $email = mysqli_real_escape_string($db, $_POST['email']); 
    $password_1 = mysqli_real_escape_string($db, $_POST['password_1']); 
    $password_2 = mysqli_real_escape_string($db, $_POST['password_2']); 
   
    // Ensuring that the user has not left any input field blank 
    // error messages will be displayed for every blank input 
    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"); 
        // Checking if the passwords match 
    } 
   
    // If the form is error free, then register the user 
    if (count($errors) == 0) { 
          
        // Password encryption to increase data security 
        $password = md5($password_1); 
          
        // Inserting data into table 
        $query = "INSERT INTO users (username, email, password)  
                  VALUES('$username', '$email', '$password')";  
          
        mysqli_query($db, $query); 
   
        // Storing username of the logged in user, 
        // in the session variable 
        $_SESSION['username'] = $username; 
          
        // Welcome message 
        $_SESSION['success'] = "You have logged in"; 
          
        // Page on which the user will be  
        // redirected after logging in 
        header('location: index.php');  
    } 
} 
   
// User login 
if (isset($_POST['login_user'])) { 
      
    // Data sanitization to prevent SQL injection 
    $username = mysqli_real_escape_string($db, $_POST['username']); 
    $password = mysqli_real_escape_string($db, $_POST['password']); 
   
    // Error message if the input field is left blank 
    if (empty($username)) { 
        array_push($errors, "Username is required"); 
    } 
    if (empty($password)) { 
        array_push($errors, "Password is required"); 
    } 
   
    // Checking for the errors 
    if (count($errors) == 0) { 
          
        // Password matching 
        $password = md5($password); 
          
        $query = "SELECT * FROM users WHERE username= 
                '$username' AND password='$password'"; 
        $results = mysqli_query($db, $query); 
   
        // $results = 1 means that one user with the 
        // entered username exists 
        if (mysqli_num_rows($results) == 1) { 
              
            // Storing username in session variable 
            $_SESSION['username'] = $username; 
              
            // Welcome message 
            $_SESSION['success'] = "You have logged in!"; 
              
            // Page on which the user is sent 
            // to after logging in 
            header('location: index.php'); 
        } 
        else { 
              
            // If the username and password doesn't match 
            array_push($errors, "Username or password incorrect");  
        } 
    } 
    
} 
   
?> 

For example I want to direct JOHN SMITH (user1) to localhost/pages/johnsmith.php and JANE SMITH (user 2) to localhost/pages/janesmith.php

just create a new redirect column in the database and set the header according to that database value.

can you please show how to do that?

this whole thing makes no sense for me, ehsserver.php looks identicaly to the login part from server.php, it even defines the credentials doubled - and then you include both? that second part will barely execute when the first part already redirects. Also you need to fix your database querying, use Prepared Statements

https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

and up-to-date password hashing

https://www.php.net/manual/en/function.password-hash.php

that’s serious security issues.

So what i want to achieve here is simply login with different users and the users have different pages. I have a server.php which works fine while login. But how do i redirect users to their respective pages using the server.php i have? Getting confused sorry.

This is what i have tried in my server.php

<?php  
  
// Starting the session, necessary 
// for using session variables 
session_start(); 
   
// Declaring and hoisting the variables 
$username = ""; 
$email    = ""; 
$errors = array();  
$_SESSION['success'] = ""; 
   
// DBMS connection code -> hostname, 
// username, password, database name 
$db = mysqli_connect('localhost', 'root', '', 'registration'); 
   
// Registration code 
if (isset($_POST['reg_user'])) { 
   
    // Receiving the values entered and storing 
    // in the variables 
    // Data sanitization is done to prevent 
    // SQL injections 
    $username = mysqli_real_escape_string($db, $_POST['username']); 
    $email = mysqli_real_escape_string($db, $_POST['email']); 
    $password_1 = mysqli_real_escape_string($db, $_POST['password_1']); 
    $password_2 = mysqli_real_escape_string($db, $_POST['password_2']); 
   
    // Ensuring that the user has not left any input field blank 
    // error messages will be displayed for every blank input 
    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"); 
        // Checking if the passwords match 
    } 
   
    // If the form is error free, then register the user 
    if (count($errors) == 0) { 
          
        // Password encryption to increase data security 
        $password = md5($password_1); 
          
        // Inserting data into table 
        $query = "INSERT INTO users (username, email, password)  
                  VALUES('$username', '$email', '$password')";  
          
        mysqli_query($db, $query); 
   
        // Storing username of the logged in user, 
        // in the session variable 
        $_SESSION['username'] = $username; 
          
        // Welcome message 
        $_SESSION['success'] = "You have logged in"; 
          
        // Page on which the user will be  
        // redirected after logging in 
        header('location: index.php');  
    } 
} 
   
// User login 
if (isset($_POST['login_user'])) { 
      
    // Data sanitization to prevent SQL injection 
    $username = mysqli_real_escape_string($db, $_POST['username']); 
    $password = mysqli_real_escape_string($db, $_POST['password']); 
   
    // Error message if the input field is left blank 
    if (empty($username)) { 
        array_push($errors, "Username is required"); 
    } 
    if (empty($password)) { 
        array_push($errors, "Password is required"); 
    } 
   
    // Checking for the errors 
    if (count($errors) == 0) { 
          
        // Password matching 
        $password = md5($password); 
          
        $query = "SELECT * FROM users WHERE username= 
                '$username' AND password='$password'"; 
        $results = mysqli_query($db, $query); 
   
        // $results = 1 means that one user with the 
        // entered username exists 
        if (mysqli_num_rows($results) == 1) { 
              
            // Storing username in session variable 
            $_SESSION['username'] = $username; 
              
            // Welcome message 
            $_SESSION['success'] = "You have logged in!"; 
              
            // Page on which the user is sent 
            // to after logging in 
            header('location: index.php'); 
             switch ($userName) {
    case "ronie":
        header('location: ehsindex.php');
        
}
        } 
        else { 
              
            // If the username and password doesn't match 
            array_push($errors, "Username or password incorrect");  
        } 
        
    }
   
    
} 
   
?> 

'select userRedirect from users where xyz'
... some user data fetching ...
header('location: '.$user->userRedirect.'.php');

sorry sir but i did not get you userRedirect indicates the user name you mean? Can you please show me the whole process? confused!! I have id,username,email and password in my users table? do i need to add rows or what?

It depends. If the redirect is always to the “username” column, then you could just redirect to that. If not, then you need a separate column.

This needs looking at, too:

  // Password matching 
        $password = md5($password); 

You should use password_hash() to store passwords, and password_verify() to check them.

Sir after the ideas i got from the early posts i have included new column called role in my user table and then it worked fine but on inclusion i have a new error showing with redirections from my index.php page?? please help.

This is my Login.php

<?php
session_start();
$conn=mysqli_connect('localhost','root','','registration');
//Getting Input value
if(isset($_POST['login'])){
  $username=mysqli_real_escape_string($conn,$_POST['username']);
  $password=mysqli_real_escape_string($conn,$_POST['password']);
  if(empty($username)&&empty($password)){
  $error= 'Fileds are Mandatory';
  }else{
 //Checking Login Detail
 $result=mysqli_query($conn,"SELECT*FROM users WHERE username='$username' AND password='$password'");
 $row=mysqli_fetch_assoc($result);
 $count=mysqli_num_rows($result);
  
 if($count==1){

      $_SESSION['user']=array(
   'username'=>$row['username'],
   'password'=>$row['password'],
   'role'=>$row['role']
   );
   $role=$_SESSION['user']['role'];
   //Redirecting User Based on Role
    switch($role){
  case 'user':
  header('location:index.php');
  break;        
  case 'moderator':
  header('location:moderator.php');
  break;
  case 'admin':
  header('location:admin.php');
  break;
 }
 }else{
 $error='Your Password or User is Wrong';
 }
}
}
?>

<html>
	<head>
		<title> NEAR MISS </title>
		<link rel="stylesheet" href="styleforlogin.css">
	        <img src="title.png" style= "width:45%; margin-left:27%;margin-top:0% ">
                <a style="margin-left:22%; color:white;" href="/Admin/login.php">ADMIN</a>
	</head>
	<body>
	<div class="loginBox">
		
		<img src="user.png" class="user">
		<h2>Login</h2>
		<form action="" method="POST">
			<p>Username</p>
			<input type="text" name = "username" placeholder="Enter ID">
			<p>Password</p>
			<input type="password" name = "password" placeholder="Enter Password">
			<input type="submit" name = "login" value="login">
                        <b style="color:white;"><?php if(isset($error)){ echo $error; }?></b>
          </form>
	</div>
	</body>
</html>


</div>
</html>

This is my index.php where i have my redirection pages which cannot be accessible anymore kindly help. I was trying to redirect to createproposal.php but it took me to the login page. sigh.

   <?php
session_start();
//Checking User Logged or Not
if(empty($_SESSION['user'])){
 header('location:login.php');
}
//Restrict admin or Moderator to Access user.php page
if($_SESSION['user']['role']=='admin'){
 header('location:admin.php');
}
if($_SESSION['user']['role']=='moderator'){
 header('location:moderator.php');
}
?>
<!DOCTYPE html>
<html>

<body>

    <head>


        <title>NearMiss</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">


    </head>

    <div class="navbar">

        <div class="dropdown">

            <button class="dropbtn"> 
					<?php echo $_SESSION['user']['username'];?>
				 
                <i class="fa fa-caret-down"></i>
            </button>

            <div class="dropdown-content">

                <a href="index.php">Home</a>
                <a href="#">Setting</a>
                <a href="logout.php">Logout</a>
            </div>
        </div>
    </div>

    <img src="title.png" style="height:50px; width:410px; padding-left:552px; margin-top:10px;">


    <div class="main">
        <div class="widget">
            <div class="title">Raised NearMiss</div>
            <div class="chart" style="font-size:13px; margin-left:30px; margin-top:22px; color: orangered; font-weight:bold;">Total Raised :  <?php require 'dbconfig.php';
                $query = "SELECT id from proposals ORDER by id";
                $query_run = mysqli_query($connection, $query);
                $row = mysqli_num_rows($query_run);
                echo  "<table>";

echo "<th style='font-size:26px; font-weight:bold; position:absolute; bottom:20px; left:62%;'>$row</th>";



echo "</table>";

                ?> </div>

            



        </div>
        <div class="widget">
            <div class="title">Pending NearMiss</div>
            <div class="chart" style="font-size:13px; margin-left:8px; margin-top:20px; color: orangered; font-weight:bold;"> Overall Pending :  <?php require 'dbconfig.php';
            $query ="SELECT * FROM `proposals` WHERE STATUS = 'pending'"; 
            $query_run = mysqli_query($connection, $query);
                $row = mysqli_num_rows($query_run);
                echo  "<table>";

echo "<th style='font-size:26px; font-weight:bold; position:absolute; bottom:20px; left:62%;'>$row</th>";



echo "</table>";


                ?>
                </div>

        </div>
        <div class="widget">
            <div class="title">Approved NearMiss</div>
            <div class="chart" style="font-size:13px; margin-left:8px; margin-top:20px; color: orangered; font-weight:bold;">Overall Approved :  <?php require 'dbconfig.php';
            $query ="SELECT * FROM `proposals` WHERE STATUS = 'approved'"; 
            $query_run = mysqli_query($connection, $query);
                $row = mysqli_num_rows($query_run);
                 echo  "<table>";

echo "<th style='font-size:26px; font-weight:bold; position:absolute; bottom:20px; left:62%;'>$row</th>";



echo "</table>";

                ?></div>
        </div>
        <div class="widget">
            <div class="title">Rejected NearMiss</div>
            <div class="chart" style="font-size:13px; margin-left:8px; margin-top:20px; color: orangered; font-weight:bold;">Overall Rejected :    <?php require 'dbconfig.php';
            $query ="SELECT * FROM `proposals` WHERE STATUS = 'rejected'"; 
            $query_run = mysqli_query($connection, $query);
                $row = mysqli_num_rows($query_run);
               echo  "<table>";

echo "<th style='font-size:26px; font-weight:bold; position:absolute; bottom:20px; left:62%;'>$row</th>";



echo "</table>";

                ?></div>
        </div>
        <div class="widget">
            <div class="title">Completed NearMiss</div>
            <div class="chart" style="font-size:13px; margin-left:8px; margin-top:20px; color: orangered; font-weight:bold;">Overall Completed :   <?php require 'dbconfig.php';
            $query ="SELECT * FROM `proposals` WHERE STATUS = 'completed'"; 
            $query_run = mysqli_query($connection, $query);
                $row = mysqli_num_rows($query_run);
                 echo  "<table>";

echo "<th style='font-size:26px; font-weight:bold; position:absolute; bottom:20px; left:62%;'>$row</th>";



echo "</table>";

                ?></div>
        </div>
    </div>

    <div class="sidenav">
        <a href="index.php" style="font-size:18px; font-family:serif;font-weight:bold; color: orangered; background-color: white;text-align:center; width:150px; margin-top:-2px;"><i style="margin-left:-36px; margin-right:4px;" class="fa fa-home"></i>
            Dashboard </a>
        <div class="accordion">
            <a href="createproposal.php" style="font-size:17px; font-family:serif;font-weight:bold; color: white;text-align:center; margin-top:2px;margin-bottom:6px; margin-left:2px;"><i style="margin-left:-45px; margin-right:3px;font-size:15px;" class="fa fa-edit"></i>Create Proposals </a>
 </div>
 <body>
 <button class="accordion"><i style="margin-left:-8px; margin-right:10px;font-size:15px;" class="fa fa-briefcase"></i>My Proposals</button>
            <div class="panel">
                <a href="pending.php"><i class="fa fa-chevron-right"></i>Pending NM</a>
                <a href="approved.php"><i class="fa fa-chevron-right"></i>Approved NM</a>
                <a href="rejected.php"><i class="fa fa-chevron-right"></i> Rejected NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Work in Progress</a>
                <a href=""><i class="fa fa-chevron-right"></i> Completed</a>
            </div>

            <button class="accordion"><i style="margin-left:-8px; margin-right:10px;font-size:15px;" class="fa fa-globe"></i>GlobalProposals</button>
            <div class="panel">
                <a href="/pending/pendingproposals.php"><i class="fa fa-chevron-right"></i> Pending NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Approved NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Rejected NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Work in Progress</a>
                <a href=""><i class="fa fa-chevron-right"></i> Completed</a>
            </div>

            <button class="accordion"><i style="margin-left:-8px; margin-right:10px;font-size:15px;" class="fa fa-envelope-open"></i>Reports</button>
            <div class="panel">
                <a href=""><i class="fa fa-chevron-right"></i> Pending NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Approved NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Rejected NM</a>
                <a href=""><i class="fa fa-chevron-right"></i> Work in Progress</a>
            </div>

            <script>
                var acc = document.getElementsByClassName("accordion");
                var i;

                for (i = 0; i < acc.length; i++) {
                    acc[i].addEventListener("click", function() {
                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.maxHeight) {
                            panel.style.maxHeight = null;
                        } else {
                            panel.style.maxHeight = panel.scrollHeight + "px";
                        }
                    });
                }

            </script>

        </body>


    </div>
    <script>
        /* Loop through all dropdown buttons to toggle between hiding and showing its dropdown content - This allows the user to have multiple dropdowns without any conflict */
        var dropdown = document.getElementsByClassName("dropdown-btn");
        var i;

        for (i = 0; i < dropdown.length; i++) {
            dropdown[i].addEventListener("click", function() {
                this.classList.toggle("active");
                var dropdownContent = this.nextElementSibling;
                if (dropdownContent.style.display === "block") {
                    dropdownContent.style.display = "none";
                } else {
                    dropdownContent.style.display = "block";
                }

            });
        }

    </script>
    <iframe src="dashboard.php" height="480" width="1230px" align="middle" style="border:1px solid orangered; margin-left: 13%; background-color:white;"></iframe>
   
</body>

</html>

Where does your code try to redirect to createproposal.php? I see a href link to it, but I can’t see a redirect to it.

In your second code, there appears to be spaces before the opening PHP tag, is that just in the forum post? If it’s there in real life, it might throw a “headers already sent” error if you don’t have output buffering enabled. I also don’t see where you open the database connection in that second piece of code, is that edited out somewhere?

sorry sir but it is the href link which i was refer to and whenever i click on that link it took me to the login page and after a go through with the whole process i found out that there was this session function missing in that file. Now it is working fine. Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.