PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
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.
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
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"?
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.
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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
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.