How do I check for permissions in a session?

I made a login page, which works fine. Every account on my system has a username, password and permission. On the login screen you only have to fill in your username and password, and the record gets automatically linked to the session, so Im sure the session knows what permission it has when logged in. I want to make a difference between a admin and a user account. An admin account should be redirected to a different screen as the user. This is my code:

if ($_SESSION['Permission'] = "admin") { 
    header("location:adminmenu.html");
} else {
    header("location:usermenu.html"); 
}

When I run this, it automatically takes me to the admin menu, even if the statement is not correct. How can I fix this?

This isnt the same, because the question isnt about parse errors.

3 answers

  • answered 2018-11-08 08:29 Rikard

    Check the following:

    1.) Use comparing instead of assigning

    if ($_SESSION['Permission'] === "admin") { 
    header("location:adminmenu.html");
    } else {
    header("location:usermenu.html"); 
    }
    

    2.) Make sure you run session_start() on each request

    3.) Make sure $_SESSION['Permission'] is set, run var_dump($_SESSION); to make sure the value is set correct.

  • answered 2018-11-08 08:38 ggwp

    Make sure when comparing values you have == and not =. Also see if there is session_start(); at the top of page.

    session_start();
    if ($_SESSION['Permission'] == "admin") { 
    header("location:adminmenu.html");
    } else {
    header("location:usermenu.html"); 
    }
    

  • answered 2018-11-08 08:49 Robert

    This is because instead of comparing you assign to $_SESSSION['Permision'] admin value and this is returned to if statement. Then in if statement it will be check if "admin" == true which in this case is true.

    The easiest way to avoid that is to use YODA Expressions with ternary operators it simplifies the code

    session_start();
    header('Location: ' . isset($_SESSION['Permission'] && 'admin' === $_SESSION['Permission'] ? 'admin' : 'user' . 'menu.html');
    

    it does the same like the code below(in terms of result)

    if (isset($_SESSION['Permission'] && "admin" === $_SESSION['Permission']) {
       header("Location: adminmenu.html");
    } else {
       header("Location: usermenu.html");
    }
    

    Notice also the present of isset() function which check if Permission exists in session array because when you don't check it then you'll get notice of non existing index