Need access for different account roles on a php page

I have two different user roles, one is Member and the other is Secretary and I need to be able to allow access to a php page if either Member or Secretary is logged in. I originally had the code below which worked if a Member role was logged in

<?php
session_start();
// If the user is not logged in redirect to the login page...
if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member') {
    include('includes/baseurl.php');        
    $title = "Show Diary - The British Rabbit Council";
    $pgDesc="";
    include ( 'includes/header.php' );
?>

I added the Secretary role to the code but it won’t allow me to access the page, I think it’s because I’m not logged in as a Member role and am logging as the Secretary role but I need access to the php page if I am logged in as either Member or Secretary

The current code I have is below

<?php
session_start();
// If the user is not logged in redirect to the login page...
if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' || $_SESSION["account_role"] != 'Secretary') {
    include('includes/baseurl.php');        
    $title = "Show Diary - The British Rabbit Council";
    $pgDesc="";
    include ( 'includes/header.php' );
?>

Can anyone help please, thank you in advance

Think I just solved it by changing a line to the following

if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' && $_SESSION["account_role"] != 'Secretary') {

If the user has two options for account role, and you want both of them to be able to access the page… dont check the role at all. Both are valid.

You dont put on your index page to check if(user_logged_in || user_not_logged_in) because… the user will always be in one of those two states. It’s a binary condition.

1 Like

Another way of doing this would to be to do something like the following

   public function enforce_security_level(array $allowedLevels): void
    {
        if (!$this->check_login_token()) {
            header('Location: login.php');
            exit();
        }

        $userLevel = $_SESSION['security_level'] ?? 'visitor';

        if (!in_array($userLevel, $allowedLevels, true)) {
            header('Location: index.php'); // Redirect unauthorized users
            exit();
        }
    }

This was a method that I wrote for a class, but could be easily modified.

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