PHP- Retrieving session variables

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
someone2088
Forum Commoner
Posts: 42
Joined: Thu Nov 17, 2011 1:09 pm

PHP- Retrieving session variables

Post 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!
mikeashfield
Forum Contributor
Posts: 159
Joined: Sat Oct 22, 2011 10:50 am

Re: PHP- Retrieving session variables

Post 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.
someone2088
Forum Commoner
Posts: 42
Joined: Thu Nov 17, 2011 1:09 pm

Re: PHP- Retrieving session variables

Post by someone2088 »

That's brilliant. Thanks
Post Reply