Page 1 of 1
Setting Sessions Inside Functions
Posted: Fri Dec 30, 2005 9:12 am
by AliasBDI
I have a function that does a few things when called. One of them is to set a SESSION variable. In my function is a SWITCH CASE and each case sets a different string to the same SESSION variable. It seems that when the page is called, all of the functions (but do not return values to the page) except the SESSIONS variable. So the SESSION is always set to the string in the last SWITCH CASE. IS this what is happening and should I try another way of setting the SESSION variable instead of a function?
Posted: Fri Dec 30, 2005 9:35 am
by twigletmac
Could we see the function code?
Mac
Posted: Fri Dec 30, 2005 9:46 am
by AliasBDI
Here you go...
Code: Select all
function lev1($lev1Name){
switch ($lev1Name){
case 1:
$_SESSION['lev1'] = 1;
break;
case 2:
$_SESSION['lev1'] = 2;
break;
case 3:
$_SESSION['lev1'] = 3;
break;
case 4:
$_SESSION['lev1'] = 4;
break;
case 5:
$_SESSION['lev1'] = 5;
break;
case 6:
$_SESSION['lev1'] = 6;
break;
case 7:
$_SESSION['lev1'] = 7;
break;
case 8:
$_SESSION['lev1'] = 8;
break;
}
}
Posted: Fri Dec 30, 2005 11:23 am
by John Cartwright
Code: Select all
function lev1($lev1Name){
$_SESSION['lev1'] = intval($level1Name);
}
Try
Posted: Fri Dec 30, 2005 12:45 pm
by Ambush Commander
That code is not "exactly" the same thing. It would accept 42 and 3.4, which likely aren't valid.
Code: Select all
function lev1($lev1Name){
if (!is_int($lev1Name) || 1 > $lev1Name || 8 < $lev1Name) return;
$_SESSION['lev1'] = (int) $lev1Name;
}
If lev1Name could be string, use this instead:
Code: Select all
function lev1($lev1Name){
if (!ctype_digit($lev1Name)) return;
$lev1Name = (int) $lev1Name;
if (1 > $lev1Name || 8 < $lev1Name) return;
$_SESSION['lev1'] = $lev1Name;
}