PHP- displaying user name on multiple pages

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- displaying user name on multiple pages

Post by someone2088 »

Hi,

I seem to be having a problem with getting a username to display on one particular page of my website.

When a user first visits the site, they login via the index.php page, after that they are taken to the home.php page, where their username is displayed. It should also be displayed on every other page they visit, until they click logout. However, on one of the pages, shoppingBasket.php, the username is not displayed for some reason.

This is the code where I am trying to display the user name on the shoppingBasket.php page:

Code: Select all

<?php 
session_start(); 
	// retrieve stored session data (not display)
	$_SESSION['userName']=$_POST['userName'];
?>


<html>
<head>
<title>Shopping Basket</title>
</head>
<body>
<h1>Shopping Basket</h1>

<?php
	// this should display session data 
	echo "Welcome ".$_SESSION['userName']."!"; 
For some reason, this code doesn't work on this page, and yet it works on both my home.php and search results pages, even though the code used on all of the pages is exactly the same:

home.php

Code: Select all

<?php 
session_start(); 
	// retrieve stored session data (this line doesn't display the session variable-
	// it only retrieves it, ready to be used elsewhere in the page).
	$_SESSION['userName']=$_POST['userName'];
?>


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

<?php
	// retrieve session data- userName (this line displays the session variable- as it
	// has already been retrieved at the top of the file.
	echo "Welcome ".$_SESSION['userName']."!";
Search results page:

Code: Select all

<?php 
session_start(); 
	// retrieve stored session data
	$minPrice=$_POST['minPrice'];
	$maxPrice=$_POST['maxPrice'];
?>


<html>
<head>
<title>Games Search By Price</title>
</head>
<body>
<h1>Search Results</h1>

<?php
	// retrieve session data
	echo "Welcome ".$_SESSION['userName']."!";
?>
Can anyone point out to me what I'm missing?

Cheers!
maxx99
Forum Contributor
Posts: 142
Joined: Mon Nov 21, 2011 3:40 am

Re: PHP- displaying user name on multiple pages

Post by maxx99 »

Before you set $_SESSION['userName'] check if $_POST['userName'] is not empty on all sites :)

Code: Select all

if(!empty($_POST['userName'])){
 $_SESSION['userName']=$_POST['userName'];
}
someone2088
Forum Commoner
Posts: 42
Joined: Thu Nov 17, 2011 1:09 pm

Re: PHP- displaying user name on multiple pages

Post by someone2088 »

That's brilliant- it works! Thanks very much!
Post Reply