Setting Sessions Inside Functions

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!

Moderator: General Moderators

Post Reply
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Setting Sessions Inside Functions

Post 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?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Could we see the function code?

Mac
AliasBDI
Forum Contributor
Posts: 286
Joined: Fri Nov 15, 2002 10:35 am
Location: Spring, TX, USA

Post 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;
	}
}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

function lev1($lev1Name){
   $_SESSION['lev1'] = intval($level1Name); 
}
Try
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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;
}
Post Reply