Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- Check for two variable in Session


Matthew1980 - 6:21 pm on Dec 27, 2011 (gmt 0)


Hi there abushahin,

Ok. The second example that has two things to be evaluated will never function (if my logic is correct) because if a $_SESSION[] isn't set (!isset($_SESSION['username'])) it wouldn't even return true. I have code on my own website for $_COOKIE/$_SESSION handling where I use empty() to see if the $_SESSION is active before I check to see if it's inuse - or isset() as these two functions: isset() and empty() are good things to use to check that a variable is instanciated && then has state, whether it's NULL or empty.

Why do you need to check that both conditions are true? Couldn't you just use nested statements to ensure that the first clause gets caught, then evaluate the second. If you're really logically minded you could even achieve this with a ternary (single line if statement - great to use, just like iif() in VB)

Try this:-

session_start();

if($_SESSION['profile'] != 2){ //checking an int() instead of string - check that it's set as such
if(!(isset($_SESSION['username']))){
header("location:index.php");
exit;
}
}

Though, I'm not too chuffed with that, and not knowning the whole context of this excerpt I don't want to stray too far away from what you've provided.

Cheers,
MRb


==============================================================================
[EDIT] Thinking about this some more, you could perhaps do something like this, well close to this, I'm a few Guinness in now so my logic head isn't 100%

session_start();
if(empty($_SESSION['username']) && !(isset($_SESSION['username'])) && ($_SESSION["profile"]!=2)){
header("location:index.php");
}

Essentially states:

$_SESSION['username'] = "" }
} - then send to the index page
$_SESSION['profile'] = 1 }

BUT, if a session is not set !isset() this potentially means that doing this: print_r($_SESSION) will mean that $_SESSION['username'] doesn't even exist in the array, so even checking for it using empty() would return false, possibly even flag an error.
====================================================================================


Thread source:: http://www.webmasterworld.com/php/4401182.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com