/    Sign up×
Community /Pin to ProfileBookmark

Session variable lost

Hi

I get users names via $_session variable. for some reason when the user goes to a the a certain page the value which is echoed in a banner on all pages gets lost. The session is still active because if I go to another page that requires the session id to make it work.

complete code

[code=php]
<?php
/* Check User Script */
session_start(); // Start Session
include (“Connections/db.php”);
//check if user is already logged in
if (!isset($_SESSION[‘user_id’])){

$msg = ‘You tryed to access a members only page. Login or become a registered member to access that page!’;

header(“Location: ../index.php?msg=”.$msg);
}
?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Buddy List</title>

<link rel=”stylesheet” type=”text/css” href=”design/niftyCorners.css”>
<link rel=”stylesheet” type=”text/css” href=”design/niftyPrint.css” media=”print”>
<script type=”text/javascript” src=”design/nifty.js”></script>

<link href=”design/main.css” rel=”stylesheet” type=”text/css” />

<script type=”text/javascript”>
window.onload=function(){
if(!NiftyCheck())
return;
<?php include(‘design/round.php’); ?>
}
</script>

</head>

<body>
<div id=”outer”>
<?php include(‘design/banner.php’); ?>

<div id=”twoColumnRight”>
<?php
if(isset($_REQUEST[‘msg’])){
echo ‘<div id=”formmessage”>’;
echo ‘<p style=”margin-left:40px;”>’.$_REQUEST[‘msg’].'</p>’;
echo ‘</div>’;
}
?>

<?php
for ($x=65; $x<=90; ++$x):
echo ‘ <a href=”mybuddies.php?index=’ .chr($x). ‘”>’ .chr($x). “</a>n”;
endfor;
echo ‘ <a href=”mybuddies.php?index=*”>ALL’.”</a>n”;
echo ‘<br />’;
echo ‘<br />’;

if($hide == “”){
echo ‘<a href=”mybuddies.php?hide=hide”>Find Buddy / Export</a>’;
}

if($hide == “hidden”) { ;
echo ‘<a href=”mybuddies.php?hide=hide”>Find Buddy / Export</a>’;
}

?>
<?php if($hide == “hide”) { ;
echo ‘<a href=”mybuddies.php?hide=hidden”>Find Buddy / Export</a>’;
?>

<form name=”searchforBuddy” method=”post” action=”Scripts/codesearch.php”>
<table class=”columntable” cellspacing=”2″ style=”width:80%;”>
<tr><td class=’tableheader’ colspan=’2′>Search for Buddies</td></tr>
<tr>
<td class=”rowLeft”><strong>First Name*</strong></td>
<td class=”rowRight”><input name=”s_firstname” type=”text” id=”s_firstname” size=”25″ /></td>

</tr>
<tr>
<td class=”rowLeft”><strong>Last Name*</strong></td>
<td class=”rowRight”><input name=”s_lastname” type=”text” id=”s_lastname” size=”25″ /></td>
</tr>
<tr>
<td colspan=”2″ class=”rowRight”><p>Click Icon to Export Address Book to <span class=”BorderGreenXbg”> Excel.The file name will be &quot;buddList&quot; with the current date at the end. Downloaded the file today ane the name would be <b>buddylist<? echo date(“Y-m-d”); ?>.xls</b></span></p>
<a class=”rowRight” href=”exportExcel.php” title=”Export Address Book”><img src=”images/excellogo.jpg” alt=”excelLogo” /></a></td>
</tr>

<tr>
<td colspan=”2″>
<input type=”submit” name=”Submit” value=”Submit” />
</td>
</tr>
</table>
</form>
<?php } ?>

<?

$active_id = $_SESSION[‘user_id’];
$buddy_id = $_POST[‘addbuddy’];
$array = explode(“,”,$buddy_id);

$post_b_id = $array[0];
$first_name = $array[1];
$last_name = $array[2];

$sql_buddy_check = mysql_query(“SELECT * FROM buddylink WHERE owner_id=’$active_id’ AND buddy_id =’$post_b_id'”);

$buddy_check = mysql_num_rows($sql_buddy_check);
if($buddy_check > 0){

echo $first_name. ‘ ‘ . $last_name. ” was found in your buddy list <br>”;

echo “<a href=javascript:history.back()>Go Back</a>”;
exit ();

}

if($buddy_id != “”){

// ADD TO TABLE
$sql = mysql_query(“INSERT INTO buddylink (owner_id, buddy_id, first_name, last_name, added)VALUES(‘$active_id’, ‘$post_b_id’, ‘$first_name’, ‘$last_name’, now())”)or die (“Link Create Error:” .mysql_error());

}

if($d_buddy != “”){

mysql_query(“DELETE FROM buddylink WHERE buddy_id = ‘$d_buddy'”);

}

$query = mysql_query(“SELECT * FROM buddylink WHERE owner_id =’$active_id’ AND status = ‘2’”) or die (“Search Error” .mysql_error());

while($r=mysql_fetch_assoc($query)) {
$buddy_user_id = $r[‘buddy_id’];
$b_id = $r[‘buddy_id’];

$index = strtoupper(substr($_GET[‘index’],0,1));
if($index != ‘*’ && (ord($index) < 65 || 90 < ord($index))) $index = ‘*’;
if($index == ‘*’) $get_buddy_info = mysql_query(“Select * From `users` WHERE user_id = ‘$buddy_user_id'”);
else $get_buddy_info = mysql_query(“Select * From `users` Where `last_name` Like ‘{$index}%’ AND user_id = ‘$buddy_user_id'”);

while($buddy_info_r=mysql_fetch_assoc($get_buddy_info)) {

$email = $buddy_info_r[’email_address’];

echo “<div class=”buddygifts”>”;
echo “<p class=’cardheader’><a href=’SearchDetails.php?owner_id=$b_id’><div class=”tableheader”>”.$buddy_info_r[‘last_name’].’,’.$buddy_info_r[‘first_name’].”</div></a></p>”;

echo “<p>”.$buddy_info_r[‘street_address’].”<br/>”. $buddy_info_r[‘post_office_box’]. ‘ ‘.$buddy_info_r[‘city’]. ‘ ‘.$buddy_info_r[‘province’].’ ‘.$buddy_info_r[‘postal’].”</p>”;
echo “<p>Phone: “.$buddy_info_r[‘home_phone’].”</p>”;
echo “<p><a href=’sendEmail.php?email=$email’>”.$buddy_info_r[’email_address’].”</a></p>”;

//get icons
$get_wish_query = mysql_query(“SELECT * FROM wishlist WHERE owner_id =’$b_id'”) or die (“Search Error” .mysql_error());
$wish_query = mysql_num_rows($get_wish_query);

if($wish_query >0){
echo “<p><a class=’emailBullet’ href=’../wishlist/buddywishlist.php?wish=$b_id’><img src=’images/gift.jpg’ alt=’gift’ title=’Go to buddies gift list’></a>”;
}else{
}

// check if found user has a photo ablum
$photoCheck = mysql_query(“SELECT * FROM images WHERE owner_id = ‘$b_id'”)or die(mysql_error());
$photo_find = mysql_num_rows($photoCheck);

if($photo_find >0){
echo “<a class=’emailBullet’ href=’photos/usersPhotoAlbum.php?owner_id=$b_id’><img src=’images/camera.jpg’ alt=’cameraBullet’ title=’See Buddies Photos’></a></p>”;
}else{
}

echo “<form name=’dBuddy’ method=’post’ action=’mybuddies.php?buddy_id=$b_id’>”;
echo “<input type=’submit’ name=’deletebuddy’ value=’Del’>”;
echo “</form>”;

echo “</div>”;
}
}
echo “<div class=”clear”></div>n”;

?>
</div>
<div id=”twoColumnLeft”>
<?php include(‘design/leftlinks.php’); ?>
</div>

<div id=”footer”>
<?php include(‘design/footer.php’); ?>
</div>
</div>

</body>
</html>

[/code]

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@NightShift58Jan 22.2007 — I think the session id is still active or else you would end up getting redirected on Line 8, which, if I understood correctly, is not what is happening.

Possibly, the problem could be a mix-up somewhere in banner.php.

Can you post banner.php?
Copy linkTweet thisAlerts:
@kprocauthorJan 22.2007 — [code=php]
<div id="banner">
<h1><a href="index.php" title="Home Page">FamilyClick.ca</a></h1>
</div>

<?php if(isset($_SESSION['user_id'])){ ?>
<div class="bannerBottom">
<ul>
<li>Welcome <? echo $_SESSION['first_name'] ." ". $_SESSION['last_name']; ?></li>
<li><a href="../logout.php">logout</a></li>
</ul>
<br clear="left">
</div>
<?php } ?>

[/code]

The css file if needed

http://familyclick.ca/design/main.css
Copy linkTweet thisAlerts:
@NightShift58Jan 22.2007 — I don't see anything that would cause it to disappear - though that doesn't mean much...

Can you add this to banner.php, somewhere near the top, to see what it "reports"?[code=php]print "<pre>";
print_r($_SESSION);
print "</pre>";[/code]
Copy linkTweet thisAlerts:
@kprocauthorJan 22.2007 — it returns all the user information,. but for some reason the first and last name is lost when the user leaves the above page.

[code=php]

[username] => proctk
[first_name] =>
[last_name] =>
[DOB] => 1979-02-22
[/code]
Copy linkTweet thisAlerts:
@NightShift58Jan 22.2007 — [code=php]
[username] => proctk
[first_name] =>
[last_name] =>
[DOB] => 1979-02-22
[/code]
How much of hassle would it be at this point to change the names of the session variables "first_name" and "last_name"? The reason is this: I [B]think[/B] I remember reading once, somewhere, something about a deadly combination of variable names, field names and session variable names running into a conflict.

In that particular page, you've got all three sources active. It could be problem. I wish I remembered where I saw this so I could point you to it. But lacking this, perhaps changing the session variable name from "first_name" to "f_name" and "last_name" to "l_name" could bring relief...
Copy linkTweet thisAlerts:
@kprocauthorJan 22.2007 — ouch, thank you for the info. I have used this session variable through my entire web page.
Copy linkTweet thisAlerts:
@NightShift58Jan 22.2007 — Since we only have the problem on this page, why not test the theory by just changing the name of the variables "$first_name" to "$f_name" and "$last_name" to $l_name".

I think they only come up twice each...
Copy linkTweet thisAlerts:
@NightShift58Jan 22.2007 — I just read something interesting which may apply.

How do visitors get to this page? Are they being redirected, i.e. header(), or just link-clicking to it?

Read this, it sounds similar to wht you're experiencing:

http://www.kirupa.com/forum/showthread.php?t=246681
Copy linkTweet thisAlerts:
@kprocauthorJan 23.2007 — I did some reading, it looks like I'm not registering my session variables correctly.

I believe this is the code completing this task please let me know what you think

// Convert password to md5 hash

$password = md5($password);

// check if the user info validates the db

$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");

$login_check = mysql_num_rows($sql);

if($login_check > 0){

while($row = mysql_fetch_array($sql)){

$last_login=$row['last_login'];

foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!

$_SESSION['username'] = $username;
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['DOB'] = $DOB;
$_SESSION['street_address'] = $street_address;
$_SESSION['post_office_box'] = $post_office_box;
$_SESSION['city'] = $city;
$_SESSION['province'] = $province;
$_SESSION['postal'] = $postal;
$_SESSION['home_phone'] = $home_phone;
$_SESSION['email_address'] = $email_address;
$_SESSION['spousefirstname'] = $spousefirstname;
$_SESSION['spouselastname'] = $spouselastname;
$_SESSION['spousedob'] = $spousedob;
$_SESSION['spousesex'] = $spousesex;
$_SESSION['user_id'] = $user_id;


note: the variables are from information in a mysql data base

thank you for the help
Copy linkTweet thisAlerts:
@NightShift58Jan 23.2007 — Is user_id also a field in your table?
Copy linkTweet thisAlerts:
@kprocauthorJan 23.2007 — yes it is
Copy linkTweet thisAlerts:
@kprocauthorJan 23.2007 — I changed the variable name to lname and fname and it fixed my problem. From what i just posted I think that im not setting session variables correctly. Is there a relationship between session variables and mysql table column names
Copy linkTweet thisAlerts:
@NightShift58Jan 23.2007 — It's what I thought but I'm still not sure where I read it - or maybe just dreamed it... Happens to old people...

I took the code you posted and mad some changes, just as a suggestion:[code=php]<?php
// Convert password to md5 hash
$password = md5($password);

// check if the user info validates the db
$sql = "SELECT * FROM users ";
$sql .= "WHERE username='$username' ";
$sql .= " AND password='$password' ";
$sql .= " AND activated='1' ";
$sql .= "LIMIT 1 ";

$sql = mysql_query($sql) or die("SQL Error: $sql<br>" . mysql_error());
$login_check = mysql_num_rows($sql);

if($login_check > 0){
while ($row = mysql_fetch_array($sql)){
$last_login = $row['last_login'];
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
$_SESSION[$key] = stripslashes($val);
}
}
}
?>[/code]
A problem could have arisen, if the user/password combination existed more than once in the table. You didn't set a limit to the query and then you were doing a WHILE loop, which could have ended up overwriting previously set session variables. Not likely but possible in a test environment....
×

Success!

Help @kproc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 12.1,
social: @webDeveloperHQ,
});

legal: ({
terms: of use,
privacy: policy
analytics: Fullres
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @aldoushuxley,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,
)...