kadota kadota - 1 month ago 7
PHP Question

Managing two different SESSION in PHP

I have a table for users in my MySQL database with a tinyint value (0 or 1) which I use to determinate the category of the user.

So, at my login.php, I get the value (stored as 'admin'):

$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
$isadmin = intval($row['admin']);


Then I assign the session:

if (password_verify($pwd, $row['password']) && $count==1){
if($isadmin==1) {
$_SESSION['admin_session'] = $row['userid'];
header("location: adminpanel.php");
} else {
$_SESSION['user_session'] = $row['userid'];
header("location: adminpanel.php");
}
}


And when it comes to check the session, I do this:

if (isset($_SESSION['user_session'])){
header("location: adminpanel.php");
exit;
} else if(isset($_SESSION['admin_session'])){
header("location: adminpanel.php");
exit;
}


But... It's not working. The page doesn't load and it shows a browser error message saying there are too many redirections being made. How can I do this?

I know both sessions are heading to the same "adminpanel.php". What I'm trying to do is both can access but once they're logged, depending on its category (whether they're admin or not), they'll be able to do certain stuff.

Answer Source

I would suggest simplifying the process and just keeping a User in the session with a flag telling you if they are an admin or not.

$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();

if (password_verify($pwd, $row['password'])){
    $_SESSION['user'] = $row['userid'];
    $_SESSION['isadmin'] = $row['admin'] == 1 ? true : false;

}

And when it comes to check the session, I do this:

if (isset($_SESSION['isadmin']) && $_SESSION['isadmin']){
    header("location: adminpanel.php");
    exit;
} else 
    // NOTE you had this redirecting exactly as above to adminpanel
    header("location: userpanel.php");
    exit;
}