Redirect from login page to other page (on the basis of User Name)

I have login page where each user redirect to same page after successfully login. But I want that redirect page should be based on username. For example If Manager login, then it should redirect to manager landing page after login and when it login to staff page then it should redirect to staff . Here is my code of login page which direct to all user on same page

<?php
// Initialize the session
session_start();
 
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: welcome.php");
    exit;
}
 
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password FROM users WHERE username = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            
            // Set parameters
            $param_username = $username;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);
                
                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();
                            
                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;                            
                            
                            // Redirect user to welcome page
                            header("location: welcome.php");
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid username or password.";
                        }
                    }
                } else{
                    // Username doesn't exist, display a generic error message
                    $login_err = "Invalid username or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<br><br><br>
<header><center> <img src = "logo.png" height = "100" width = "180"></center></header>
 <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card mt-5">
                    <div class="card-header" style="background-color: #3fbbc0;">
                        <h4>Login</h4>
                    </div>
                    <div class="card-body">

        <?php 
        if(!empty($login_err)){
            echo '<div class="alert alert-danger">' . $login_err . '</div>';
        }        
        ?>


        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="col-md-12">

                <label>Username</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>    
<div class="col-md-4">
                <label></label>
             
            </div>    
            <div class="col-md-12">
                <label>Password</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
<div class="col-md-4">
                <label></label>
               <label></label>
            </div>
            <div class="form-group">
               <center> <input type="submit"  style="background-color: #3fbbc0;" value="Login">
            </div>
         
        </form>
    </div>
</body>
</html

The redirect upon successful completion of the post method form processing code should be to the exact same url of the post method form processing code. This causes a get request for that page. This will prevent the browser from trying to resubmit the form data if that page is reloaded or browsed back to, where someone can use the browser’s developer tools, network tab, to see what the submitted username and password is for the last person to log in.

To allow the user to go to a different page after successfully logging in, provide navigation links, or more simply, just integrate the login operation on any page that needs it.

I am trying to create login page where each user redirect to page should be based on username. For example If Manager login, then it should redirect to manager landing page after login and when it login to staff page then it should redirect to staff . Here is my code of login page . But my code is generating error and not working . mysql table have user name “user” with four column which are (id, username, password and user_redirect_uri) Here is the code

<?php
// Initialize the session
session_start();
 
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
      header('Location: $url');
    exit;
}
 
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
     $sql = "SELECT id, username, password, user_redirect_uri FROM users WHERE username = ? AND password = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_result($stmt,  $id, $username, $hashed_password, $url);
            
            // Set parameters
            $param_username = $username;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);
                
                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();
                            
                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;                            
                            
                            // Redirect user to welcome page
                          
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid username or password.";
                        }
                    }
                } else{
                    // Username doesn't exist, display a generic error message
                    $login_err = "Invalid username or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<br><br><br>
<header><center> <img src = "logo.png" height = "100" width = "180"></center></header>
 <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card mt-5">
                    <div class="card-header" style="background-color: #3fbbc0;">
                        <h4>Login</h4>
                    </div>
                    <div class="card-body">

        <?php 
        if(!empty($login_err)){
            echo '<div class="alert alert-danger">' . $login_err . '</div>';
        }        
        ?>


        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="col-md-12">

                <label>Username</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>    
<div class="col-md-4">
                <label></label>
             
            </div>    
            <div class="col-md-12">
                <label>Password</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
<div class="col-md-4">
                <label></label>
               <label></label>
            </div>
            <div class="form-group">
               <center> <input type="submit"  style="background-color: #3fbbc0;" value="Login">
            </div>
         
        </form>
    </div>
</body>
</html>

Y’ know, when you’re asking for help with your code and it generates an error it is a good idea to say what the error says…

Did you read the reply in your last thread for this almost identical code about how to prevent someone from being able to see the username and password that was entered in the login form?

Next, the differences between that code and this code involve a variable that doesn’t exist ($url in the 1st redirect, that won’t work if it did exist because it is inside a single-quoted string), an sql query that will never match anything (you cannot match the hashed password in the query, you must fetch the hashed password and use password_verify() to test for a match, like the original code was doing correctly), and incorrectly changed the mysqli_stmt_bind_param() statement into a mysqli_stmt_bind_result() statement.

I recommend that you (re)read the reply you got in the previous thread for this code and switch to the much simpler PDO database extension. Over half of the database specific lines of code will go away and you won’t need to deal with explicit binding, since you can simply supply an array of input values to the ->execute([…]) call and can directly fetch data from the query.

Well no. You need a redirect to prevent the back button from reposting but it can be to anywhere.

If the original posted code was working then all that would be needed was a slight tweak to header("location: welcome.php");.

I don’t find anything NOT working but the default redirect to the “welcome” page might be a bit annoying around line 7 and so you should probably set the user_redirect_uri to session from the query result and use that to direct the user back to their home page,

$_SESSION["usersection"] = $url;

This is my edited version.

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: ".$_SESSION["usersection"]);
    exit;
}
 
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
		
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password, user_redirect_uri FROM users WHERE username = ?";        										 	
						
        if($stmt = mysqli_prepare($link, $sql)){
				
					// Bind variables to the prepared statement as parameters
					mysqli_stmt_bind_param($stmt, "s", $param_username);
					
					// Set parameters
					$param_username = $username;
										
					// Attempt to execute the prepared statement
					if(mysqli_stmt_execute($stmt)){	
					    // Store result
					    mysqli_stmt_store_result($stmt);
					    
					    // Check if username exists, if yes then verify password
					    if(mysqli_stmt_num_rows($stmt) == 1){                    
					        // Bind result variables
					        mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password, $url);	
					
					        if(mysqli_stmt_fetch($stmt)){
					            if(password_verify($password, $hashed_password)){
					                
					                // Store data in session variables
					                $_SESSION["loggedin"] = true;
					                $_SESSION["id"] = $id;
					                $_SESSION["username"] = $username;
					                $_SESSION["usersection"] = $url;                            
					                
					                // Redirect user to home page
					                header("location: ".$url);
													exit;
					            } else{
					                // Password is not valid, display a generic error message
					                $login_err = "Invalid username or password.";
					            }
					        }
					    } else{
					        // Username doesn't exist, display a generic error message
					        $login_err = "Invalid username or password.";
					    }
					} else{
					    echo "Oops! Something went wrong. Please try again later.";
					}
				}
				// Close statement
				mysqli_stmt_close($stmt);
    }
    
    // Close connection
    mysqli_close($link);
}
?>

ALSO, learning how to debug your own code is an important part of being a a code writer.
When I initially was working with your code it “didn’t work” and without seeing any obvious errors I was stumped for a bit. SO I wrote this complex line of code.

echo "HI";

I know that’s tricky but I then started moving this line down the processing section and kept testing submitting the form until I got to a point where I was NOT seeing HI anymore. I then knew that it was line before this that was giving me trouble. In my case it was

if($stmt = mysqli_prepare($link, $sql)){

So it was a problem with the query or the DB connection. I then noticed that when I created the testing DB users table I added the field user_redirect_url but the query is calling the field user_redirect_uri and so after changing the field so they match, all is working fine…

SO the problem is NOT always in the code per-say as it doesn’t care if it’s uri or url but the field names used need to match what is in the DB.

ok thanks alot sir! it really helped me alot . Now I am facing another issue . My login table in mysql have role field too. I want when user login by entering username and password, then it should check role on specific page. Here is my session code on top of each page. what changes I need to add in that so that it can check role from database table

session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION[“loggedin”]) && $_SESSION[“loggedin”] === true){
header(‘Location: $url’);
exit;
}

Either Set the “role” of the user (Admin/Manager whatever) to session when they log in and define the role on the page(s) and compare the two.
OR
We had already talked about setting their home page to session, i.e. $_SESSION["usersection"], so then on each page you define the section with the same url as used in the user table.

So say for example an Admin user might be directed to Admin/index.php, then on all Admin pages you define $section = "Admin/index.php"; the compare $section to $_SESSION["usersection"] so if they match, all is good and they are supposed to be there, if not kick them out.

Also note: $url is not present on all pages so send them somewhere where you can control what happens like a login page. You could log them out or use $_SESSION["usersection"] to send them where they should be.

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