Search code examples
phphtmlsessionsession-cookies

User Login with roles not working properly in PHP


I have created a table in my db as user and I have assigned the accounts with the user types as Admin,User,Vendor.

I have 3 seperate dashboards created for each of the roles. When I login to the system the redirection works totally fine. But when I insert the url of the dashboard of the another type of user the page loads without any redirection.

when I log in as User and if I insert the following url in the browser admin page loads for a general user.

http://localhost:3002/Admin/dashboard.php

I cannot figure out what's wrong in my code.

This is my php code for login control

    <?php
    session_start();

    include('./validate.php');
    require_once('../Includes/db/dbConnection.php');
    $db = DBConnection::getInstance();
    $connection = $db->getConnection();

    if(isset($_POST['btnLogin'])){
        $username=validate($_POST['uname']);
        $pass=validate($_POST['psw']);
        
        $sql="SELECT userId,userType FROM user WHERE username='$username' AND password='$pass'";
        $res=mysqli_query($connection,$sql);
        $count=mysqli_num_rows($res)>0;
        if($count>0){
            $row=$res->fetch_assoc();
            $_SESSION['userId']=$row['userId'];
            $_SESSION['username']=$username;
            $_SESSION['userType']=$row['userType'];
            $_SESSION['loggedIn']='true';
            switch ($_SESSION['userType']){
                case 'User':
                    header("location: ../User/dashboard.php");
                    break;
                case 'Admin':
                    header("location: ../Admin/dashboard.php");
                    break;
                case 'Vendor':
                    header("location: ../Vendor/dashboard.php");
                    break;
                default:
                   
                    break;
            }
        }else{
           $_SESSION['status']='Wrong Username/Password';
           header("Location: ../login.php"); 
        }
    }

?>

This is the code I use in the dashboard.php file for each user.

Admin

<?php
    session_start();
    if(!isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']!='true' && $_SESSION['userType']!='Admin'){
        header("Location: ../login.php");
    }  
?>

User

<?php
    session_start();
    if(!isset($_SESSION['loggedIn']) && $_SESSION['loggedIn']!='true' && $_SESSION['userType']!='User'){
        header("Location: ../login.php");
    }  


?>

What am I doing wrong ?


Solution

  • You need to use OR in this check not AND

    <?php
    session_start();
    if(!isset($_SESSION['loggedIn']) || 
        $_SESSION['loggedIn']!='true' ||
        $_SESSION['userType']!='User')
    {
        header("Location: ../login.php");
        exit;
    }