Page 1 of 1

Simple and wont work

Posted: Tue Oct 14, 2008 4:17 pm
by veldthui
I have a problem with a simple bit of code and can't work out why it does not work.
I am trying to redirect if a person has not logged in and their level does not equal admin. The logged in part work but the second part always fails and allows access.

Code: Select all

if (!isset($_SESSION['guid']) && ($_SESSION['level'] != "admin")) {
    $_SESSION['redirect'] = "staff.php"; // We will come back to this page when done.
    redirect_to("login.php");
}
The isset part works and if guid is not set then it redirects but no matter what level is it goes past it as though it was admin. guid should be set and level = admin to go through.

Any answers to what should be really obvious to a newbie.
Thanks.
John Veldthuis

Re: Simple and wont work

Posted: Tue Oct 14, 2008 4:53 pm
by Ziq

Code: Select all

 
if (!isset($_SESSION['guid']) || ($_SESSION['level'] != "admin")) {
$_SESSION['redirect'] = "staff.php"; // We will come back to this page when done.
redirect_to("login.php");
}
 
Do you want, that the user can log in only if level set as "admin"?

Re: Simple and wont work

Posted: Tue Oct 14, 2008 5:38 pm
by veldthui
No, Only to restrict access to certain pages. Some pages anyone logged in can access but others such as adding a new user I want to restrict to those that have admin as a level. Everything appears to work by itself (eg the user is logged in or the level = admin) but as soon as I put it in the && condition it does not work as I would expect it to.

Re: Simple and wont work

Posted: Tue Oct 14, 2008 5:44 pm
by pickle
~Ziq's code should work.

The && means both conditions must be met. So, the user has to be not logged in, and the user must not have the correct level. That will work fine for someone that isn't logged in. However, if someone of level "bottom of the barrel user" tries to access the page, first part of the boolean statement will fail, and the code inside the if(){} statement will never run.

What you want is an OR - so if either of the conditions evaluate true, the statement evaluates to true.

Re: Simple and wont work

Posted: Tue Oct 14, 2008 6:19 pm
by veldthui
Thanks, I did have an OR originally and it did not appear to work properly either (man I hate logic). I decided to make it more generic and turned it into a function so that it now uses an array of levels. I pass in the level of the user, the levels that are allowed access to the page and then return true or false based on that. Seems to work and is a lot more useful later on.
Thanks for the help.