Basic session question

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
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Basic session question

Post by psurrena »

Code: Select all

if (isset($_POST['add'])) {				
	$fname = $_POST['fname'];
	$_SESSION['fname'] = $fname;
	header ('location:test2.php');
}

Everything works, I was just wondering why

Code: Select all

$_SESSION['fname'] = $fname;
works but

Code: Select all

$fname=$_SESSION['fname'];
does not...
decipher
Forum Commoner
Posts: 38
Joined: Mon Mar 13, 2006 6:27 am
Location: south africa

Post by decipher »

Code: Select all

$fname=$_SESSION['fname'];
will not work if $_SESSION['fname'] has not been set

you can use the following to set $fname to the value of the session if it exists, else set a default value.

Code: Select all

$fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : "nothing";
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

session_start() ?
User avatar
iknownothing
Forum Contributor
Posts: 337
Joined: Sun Dec 17, 2006 11:53 pm
Location: Sunshine Coast, Australia

Post by iknownothing »

by looking at your example, you want the contents of $fname in your session variable. The way that it is in your example works because $fname has been given a value, then is passing it on to the session variable, the other way will not work because there is no data within the session variable at the time to give its data to $fname.

If you wanted to get the session variable data on a separate page, after the first example has been run, then you could use the second example to put your session data into the $fname variable
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Post by psurrena »

Makes sense - thanks a lot!
Post Reply