Skip to main content
Participating Frequently
October 4, 2012
Answered

Prevent access by access level

  • October 4, 2012
  • 1 reply
  • 1544 views

I have set up a login system that has 3 access levels: admin, level1 and level2. The access levels are stored in a session, MM_UserGroup. I need to protect some pages from being opened by typing in their URL direct - ie they should only be able to be opened if the user is logged in under the usergroup 'admin'. Can't seem to work out the code to do this - it's probably very simple. Something like

session_start();

if (!isset($_SESSION['MM_UserGroup']=='admin'))

{

header ("Location: login.php");

}

ie if the session is not opened by an admin level user then redirect to the login page, otherwise continue to open the page.

This topic has been closed for replies.
Correct answer David_Powers

That's what I thought - however using this code redirects both admin and level1 back to the login page. They both work OK if I just have the single conditional statement as before. What I am trying to achieve is to allow access to all pages by admin, with some pages also accessible by level1 but not level2, and other pages also accessible by level2 but not level1.


nfhopmike2 wrote:

That's what I thought - however using this code redirects both admin and level1 back to the login page.

Catches me out every time. The problem is using two negative comparisons. A conditional statement stops as soon as it reaches a TRUE value. Because "level1" is not "admin", $_SESSION['MM_UserGroup'] != 'admin' returns TRUE. As a result, $_SESSION['MM_UserGroup'] != 'level1' is never tested.

You need to rewrite the condition like this:

if (!isset($_SESSION['MM_UserGroup']) ||

    !($_SESSION['MM_UserGroup'] == 'admin' ||

    $_SESSION['MM_UserGroup'] == 'level1'))  {

      header('Location: login.php');

      exit;

}

This uses positive comparisons for "admin" and "level1", and wraps the alternatives in a pair of parentheses preceded by an exclamation mark. If the session variable is neither "admin" nor "level1", it returns TRUE, causing the user to be redirected.

1 reply

David_Powers
Inspiring
October 6, 2012

You can't mix isset() and the equality operator like that.

Change your code to this:

session_start();

if (!isset($_SESSION['MM_UserGroup']) || $_SESSION['MM_UserGroup'] != 'admin') {

    header('Location: login.php');

    exit;

}

Participating Frequently
October 7, 2012

Thank you David that is very helpful. How would I change this code if I wanted to allow both admin and level1 users acess to the page?

David_Powers
Inspiring
October 7, 2012

Just add another condition at the end of the if() clause.

session_start();

if (!isset($_SESSION['MM_UserGroup']) || $_SESSION['MM_UserGroup'] != 'admin' || $_SESSION['MM_UserGroup'] != 'level1') {
    header('Location: login.php');
    exit;
}