Page 1 of 1

PHP- Retrieving session variables

Posted: Wed Nov 23, 2011 6:20 am
by someone2088
I'm trying to write a website which will start a session, and maintain it throughout, or until the user selects 'log out'. I need to ask the user's name, and then display it on every subsequent page, but I'm having a bit of trouble retrieving and displaying the data stored in a PHP session variable.

So far, the code for my index.php page looks like this:

Code: Select all

<?php session_start(); 
// Store session data. 
$_SESSION['userName']=userName;
?>

<html>
<head>
<title>Log in</title>
</head>
<body>
<h1>Log In</h1>

<form action="home.php" method="post">
Name: <input type="text" name="userName" />
<input type="submit" value="Submit" />
</form>



</body>
</html>
After entering their name, and selecting 'submit' the user is taken to the home page, which looks like this:

Code: Select all

<?php session_start(); 
	// register session variables
	session_register('userName');
	// store posted values in the session variables
	$_SESSION['userName']=$_POST['userName'];
?>

<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Home</h1>

<?php
Welcome echo $_SESSION["userName"]; ?>!

<?php
What I want to happen is that when the user enters their name and clicks 'submit' on the index page, they should be taken to the home page, where a welcome message is displayed along with their name. At the moment, all that's displayed on the home page is the ! Could someone point out to me what I'm doing wrong?

Thanks in advance!

Re: PHP- Retrieving session variables

Posted: Wed Nov 23, 2011 6:59 am
by mikeashfield

Code: Select all

<?php
    session_start();
    $_SESSION['name'] = $_REQUEST['name'];
    echo "Welcome ".$_SESSION['name']."!";
?>
You had the word welcome before the echo, so PHP juddered and stopped.

Code: Select all

echo "Welcome ".$_SESSION['name']."!";
should fix it.

Re: PHP- Retrieving session variables

Posted: Fri Nov 25, 2011 8:04 am
by someone2088
That's brilliant. Thanks