Search code examples
phpmysqlauthenticationadmindashboard

Redirecting user to dashboard with their user role from same login page


I have directed user according to the user's role in the dashboard from the same login page.

But with this the user can go to user dashboard just by simple providing the admins url.

How can I prevent a user from getting in the admin dashboard after login?

The login code is as follow.

if(isset($_POST['login'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    //if the user try to enter without typing anything.
    if($username !="" && $password !==""){
        /*$password = sha1($password);*/
        $sql = "SELECT * FROM users WHERE username ='$username'AND password='$password'";

        $result=mysqli_query($conn, $sql) or die('Error');
        if(mysqli_num_rows($result) > 0){

            while($row = mysqli_fetch_assoc($result)){
                $user_id = $row['user_id'];
                $fullname = $row['fullname'];
                $username = $row['username'];
                $phone_number = $row['phone_number'];
                $state = $row['state'];
                $city = $row['city'];
                $street = $row['street'];
                $email = $row['email'];
                $user_role = $row['user_role'];


                //Starting the session for the user
                $_SESSION['user_id'] = $user_id;
                $_SESSION['fullname'] = $fullname;
                $_SESSION['username'] = $username;
                $_SESSION['phone_number'] = $phone_number;
                $_SESSION['state'] = $state;                
                $_SESSION['city'] = $city;
                $_SESSION['street'] = $street;
                $_SESSION['email'] = $email;
                $_SESSION['user_role'] = $user_role;
                if($user_role == admin){
                    header('Location:admin/admindashboard.php');
                }else{
                    header('Location:user/userdashboard.php');
                }
            }
        }else{
            $error="Username or Password is incorrect!!";
        }
    }else{
        $error = "Please Enter Username and Password";
    }
}

Solution

  • You need to make sure that certain conditions match for each user so that they do not navigate by typing into URL.

    From your coding assuming that you have already redirected the users to the relevant page. Make sure you have validation checks in following files.

    Add this to the header of admindashboard.php

    if( $_SESSION['user_role'] != "admin")
    {
        session_destroy();
        header("location: login.php");
    }
    

    Add this to the header of userdashboard.php

     if( $_SESSION['user_role'] != "user")
        {
            session_destroy();
            header("location: login.php");
        }
    

    With the above codes, you will block other different types of users accessing different parts of the website.