Setting Sessions Inside Functions
Moderator: General Moderators
Setting Sessions Inside Functions
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?
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
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;
}
}- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Code: Select all
function lev1($lev1Name){
$_SESSION['lev1'] = intval($level1Name);
}- Ambush Commander
- DevNet Master
- Posts: 3698
- Joined: Mon Oct 25, 2004 9:29 pm
- Location: New Jersey, US
That code is not "exactly" the same thing. It would accept 42 and 3.4, which likely aren't valid.
If lev1Name could be string, use this instead:
Code: Select all
function lev1($lev1Name){
if (!is_int($lev1Name) || 1 > $lev1Name || 8 < $lev1Name) return;
$_SESSION['lev1'] = (int) $lev1Name;
}Code: Select all
function lev1($lev1Name){
if (!ctype_digit($lev1Name)) return;
$lev1Name = (int) $lev1Name;
if (1 > $lev1Name || 8 < $lev1Name) return;
$_SESSION['lev1'] = $lev1Name;
}