Link to home
Start Free TrialLog in
Avatar of team2005
team2005

asked on

My session get changed ?

Hi!

Have a form that registrate new golf clubs. Have set a session variabel called -> logoclub
When i call the page with the form, its show all fields, and my session is set to 14

But after i hit the button on the form, the session is changed ?
What is going on here ?



<?php
/**
 * Author: Tor Erik Berg
 * Version: 0.98 
 * 
**/

if($_REQUEST['save_golfclub'] && $_REQUEST['mem_first_name'] && $_REQUEST['mem_last_name']){
	session_start();
	
	
	$golfclub_id2=(int)$_SESSION['logoclub'];
    echo "GOLDKLUBB ID START:".$golfclub_id2;
	die();
	
	$golfklubnavn = $newsletter->get_golfclubname($db,$_REQUEST['mem_golfclub']);
	$fields = array(
		"brukernavn"=>htmlspecialchars($_REQUEST['mem_first_name']),
		"passord"=>htmlspecialchars($_REQUEST['mem_last_name']),
		"emailbounce"=>htmlspecialchars($_REQUEST['mem_email_bounce']),
		"emailfra"=>htmlspecialchars($_REQUEST['mem_email_fra']),
		"golfclub"=>htmlspecialchars($_REQUEST['mem_golfclub']),
		"navnklubb"=>htmlspecialchars($golfklubnavn),
	);
	$message="START : ";
	
	//echo "<script type='text/javascript'>alert('$message');</script>";
	$golf_id = $newsletter->save_golfclub($db,$fields);
	
	if($golf_id){
		
		ob_end_clean();
		//header("Location: index.php?p=golfklubb");
		exit;
	}
	
}


?>

<form action="" method="post" id="create_form">
<input type="hidden" name="member_id" value="new">
<input type="hidden" name="save" value="true">

<div class="box">
	<?php include("golfklubb_form.php"); ?>
</div>

</form>

Open in new window



<?php



$newsletters = $newsletter->get_golfclubs($db);

//echo "ID GOLF 2 : ".$golfclub_id;
//die();
?>
<!--  Hate tables but need them -->
<h2><span>Legg til ny klubb</span></h2>
  <table cellpadding="5">
	
		<tr>
			<td>
			  <label>Golf Klubb</label>
			</td>
			<td>
				<div class="form_field"><select name="mem_golfclub" id="golfclub">
			
					<?php 
					
					foreach($newsletters as $newsletter){
						?>
						<option value="<?php echo $newsletter['golf_id'];?>"><?php echo $newsletter['namegolf'];?></option>
						<?php
					}
					?>
				</select>
				
				</div>
			</td>
		</tr>
		<tr>
			<td>
				<label>Brukernavn</label>
			</td>
			<td>
				<div class="form_field"><input type="text" name="mem_first_name" id="first_name" value="<?php echo $member_data['first_name'];?>"></div>
			</td>
		</tr>
		<tr>
			<td>
				<label>Passord</label>
			</td>
			<td>
				<div class="form_field"><input type="text" name="mem_last_name" id="last_name" value="<?php echo $member_data['last_name'];?>"></div>
			</td>
		</tr>
	<tr>
			<td width="200px;">
				<label>Bounce Email</label>
			</td>
			<td width="300px;">
				<div class="form_field"><input type="text" name="mem_email_bounce" id="bouemail" value="<?php echo $member_data['email'];?>"></div>
			</td>
		</tr>
		
		<tr>
			<td width="200px;">
				<label>Fra Email</label>
			</td>
			<td width="300px;">
				<div class="form_field"><input type="text" name="mem_email_fra" id="fraemail" value="<?php echo $member_data['email'];?>"></div>
			</td>
		</tr>
		
		<tr>
			<td>
				
			</td>
			<td>
				<div class="buttons">
				 <input type="submit" name="save_golfclub" value="Lagre klubb" class="button">
		    </div>
		 	</td>
		</tr>
		
	</table>
	
	<h2><span>Registrerte golfklubber:</span></h2>

<div class="box">
	<table cellpadding="5" class="stats">
		<tr>
			<th>Golf klubb</th>
			<th>Brukernavn</th>
			<th>Passord</th>
			<th>Bounce Email</th>
			<th>Fra Email</th>
			<th>Status</th>
			<th>Registrert</th
		</tr>	
	</table>
</div>

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You need to put
session_start()

Open in new window

At the top of each script that is session aware
Avatar of team2005
team2005

ASKER

Hi!

I have included session_start() ?
Here is how to use the PHP session.  It's usually pretty easy.  One of the first and most important rules: Always use session_start() unconditionally.  In the code snippet here, it's inside an if() control structure, implying that if the if() is not TRUE, the session_start() statement will not get executed.  And session_start() does not appear at all in the second code snippet.  You probably want to fix that immediately, but first have a look at this article.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html

To see what is contained in the $_SESSION array, you can use var_dump()
Also, now that I've read the code in a little more detail, we do not use HTMLSpecialchars() before putting data into a database table.  It's more appropriate to escape the fields.  HTMLSpecialchars() is used before echoing data to the client browser.  If you're new to PHP and want to find some good learning resources, this article can help you find those, and more importantly, it can help you avoid the many terrible, obsolete examples of PHP code that litter the internet.  It's hard to know what you can depend on if you're just looking for examples, because PHP is 20+ years old and many of the example you can find "at random" are so old that they contain dangerous security holes, or other errors of design.  So stick with the learning resources here, and you'll be better off!
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
I have included session_start() ?
I don't see it in the listing you posted?
@Julian: It looks like session_start() is inside a conditional statement in the first snippet and not present at all in the second snippet.  That's why I think it may be good for our author to step back from this task and take a little time with the basics!  There are so many things that can go wrong here... Interplay of $_SESSION  and $_REQUEST, if() statements without else{} clauses, undefined variables, PHP code mixed into HTML documents, etc.  My sense is that it would probably be better to start over and redesign the application using 21st century guidelines.
@Ray, missed the first listing one. Agreed on the design comment.

The use of session_start() in the first is also dodgy - based on a conditional statement which is going to create issues.

session_start should come at the top of all the scripts that need to use sessions.
Hi!

My PHP-file is called 1 time only, and session is lost ?

Tryed to print out sessions variables, and it shows
Array ( [user_logged_in] => softkey [logoclub] => 6 [logoclubname] => imagecustomer/ [statuslogin] => [golfclubname] => Atlungstad Golfklubb [_newsletter_loggedin] => 1 )

  [user_logged_in]  is not changed OK
[logoclub]  => 6 is changed from 14 to 6 ?????

Olso  [golfclubname] => Atlungstad Golfklubb is changed ??
Hi!

I have not made this code in the first place.
Just modify some code.

My big question is why session variable is changed ?
Something is still missing - where are you setting the SESSION variables?

The only place you access the SESSION is on line 12 of the first listing and that is on the right side of the equals
	$golfclub_id2=(int)$_SESSION['logoclub'];

Open in new window

Where are the left side assignments?

It sounds like you might have a cache problem. Clear the cookies for the page and try again.
My PHP-file is called 1 time only, and session is lost ?
This misses the point of sessions.  The whole idea of sessions is to allow data to persist across multiple HTTP requests.  A file that is called one time only has only one HTTP request, so persistent data is not an issue.  You have to be calling a file or files via more than one HTTP request to get value from the session.

If you've read the article about PHP sessions and you fully understand it, the next step is to make sure you have a web server / browser setup that works correctly.  Install and run this script, exactly as written here.  If it increments and decrements the variable as you would expect, your PHP session setup is working correctly and there is a logic error in your code, probably in some place we have not seen yet.  If this fails, we can begin to work on the many possible configuration variables (mostly called out in the article on PHP sessions) that can impede session handling.

Your copy of this script should work the same way as my copy of this script, linked here:
http://iconoun.com/demo/session_test.php
<?php // demo/session_test.php

/**
 * Demonstrate how PHP sessions work
 * Ref: http://php.net/manual/en/function.session-start.php
 * Ref: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909.html
 */
error_reporting(E_ALL);

// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (!isset($_SESSION["counter"])) $_SESSION["counter"] = 0;

// SEE IF THE INCREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['bump']))
{
    // ADD ONE TO THE COUNTER
    $_SESSION['counter']++;
}

// SEE IF THE DECREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['dump']))
{
    // TAKE ONE FROM THE COUNTER
    $_SESSION['counter']--;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$counter = $_SESSION['counter'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["counter"] contains: $counter<br/>
<form method="post">
<input type="submit" value="decrement this counter" name="dump" />
<input type="submit" value="leave my counter alone" name="keep" />
<input type="submit" value="increment this counter" name="bump" />
</form>
</body>
</html>
ENDFORM;

echo $form;

Open in new window

Hi!

Try to ask in a differen way:

'm using SESSIONS to store data from a database when a user logs in. However, when I query a database on another page the SESSION variables change without me assigning new values to them.

Does anyone know what the problem could be?

Some of my SESSION variables get changed, but strugle to find out where it do this

Include my index.php file to:

<?php

if(version_compare(PHP_VERSION, '5.0.0', '<')){
	echo "I'm sorry, PHP version 5 is needed to run this website. <br>";
	echo "The current PHP version is: ". phpversion() . "<br>";
	echo "Ask your hosting provider to upgrade it for you.";
	exit;
}
define("_NEWSLETTER_VERSION",1.0);

session_start();


header('Content-Type: text/html; charset=UTF-8');


ob_start();// so we can header:redirect later on


if(is_file("php/config.php")){
	require_once("php/config.php");
}

require_once("php/functions.php");
require_once("php/class.newsletter.php");

$newsletter = new newsletter();

		
if(defined("_DB_NAME")){
	
	require_once("php/database.php");
	
	$db = db_connect();
	
	if($_REQUEST['p']!='setup'){
		$newsletter->init();
		require_once("php/auth.php");
	}

}



$show_menu = (isset($_REQUEST['hide_menu'])) ? false : true;


$sql = "SELECT * FROM `"._DB_PREFIX."loginadmin` WHERE golf_id = '".mysql_real_escape_string($_SESSION['logoclub'])."'";
$res = array_shift(qa($sql,$db));
$folder = _LOGOER_DIR.''.$res['namelogo'].'';

$statuslogin = $res['status'];

 //Print_r ($_SESSION);
 

if ($_SESSION['logoclub']){
	$_SESSION['logoclubname']= $folder;
	$_SESSION['statuslogin']= $statuslogin;
	$_SESSION['golfclubname']= $newsletter->get_golfclubname($db,$_SESSION['logoclub']);
	//$_SESSION['golfclubname']="HONA";
}


ob_start();
if(defined("_DB_NAME") && $show_menu){ ?>
<?php } ?>
	<?php if(defined("_DB_NAME")){ ?>
		<?php if($show_menu){ ?>
		<div class="navbar">
			<div class="navbar-inner">
				<div class="container">
				<ul class="nav">
					<span class="site_icon"><img src="<?php echo $_SESSION['logoclubname']; ?>" alt="tutlage_icons" /></span>
					<span class="spacer">&nbsp;</span>
					<li><a href="?p=home"> Hovedside </a></li>
						<li class="divider-vertical"></li>
					<li class="dropdown">
						<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Nyhetsbrev <b class="caret"></b> </a>
						<ul class="dropdown-menu">
							<li><a href="?p=create"> Lage Nyhetsbrev</a></li>
							<li><a href="?p=past"> Vise Nyhetsbrev </a></li>
						</ul>
					</li>
					<li class="divider-vertical"></li>
					<li class="dropdown">
						<a href="?p=campaign" class="dropdown-toggle" data-toggle="dropdown"> Kampanje </a>
					</li>
					<li class="divider-vertical"></li>
					<li class="dropdown">
						<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Medlemmer <b class="caret"></b> </a>
						<ul class="dropdown-menu">
							<li><a href="?p=members_add"> Legg til medlem </a></li>
							<li><a href="?p=members"> Vise Medlemmer </a></li>
						</ul>
					</li>
					<li class="divider-vertical"></li>
					<li class="dropdown">
						<a href="?p=groups" class="dropdown-toggle" data-toggle="dropdown"> Nyhetsgrupper </a>
					</li>
					<li class="divider-vertical"></li>
					<li class="dropdown">
						<a href="?p=settings" class="dropdown-toggle" data-toggle="dropdown"> Settings </a>
					</li>
                    <?php if($statuslogin==99){ ?>
					   <li class="dropdown">
						<a href="?p=golfklubb" class="dropdown-toggle" data-toggle="dropdown"> Golfklubb </a>
					</li>
					<?php }?>

				</ul>
				<ul class="nav pull-right">
					<li class="dropdown">
						<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Velkommen <?php echo $_SESSION['golfclubname']; ?> <b class="caret"></b> </a>
						<ul class="dropdown-menu">
							<li> <a href="?logout"> Logg ut </a></li>
						</ul>
					</li>
				<ul>

				</div><!-- end container -->
			</div><!-- end navbar-inner -->
		</div><!-- end navbar -->

	<div class="innerContent">
		<?php
		}
		$page=false;
		if(isset($_REQUEST['p'])){
			$page = basename($_REQUEST['p']);
		}
		if(!$page || !is_file("php/pages/".$page.".php")){
			$page = "home";
		}
		include("php/pages/".$page.".php");
	
	}else{
		
		include("php/pages/setup.php");
	}
	?>
	</div>
<?php
$inner_content = ob_get_clean();
include("layout/system_header.php");
echo $inner_content;
include("layout/system_footer.php");
?>

Open in new window

Can you describe how they "get changed" - some examples?

There are several things that you would need to look at - including locating your session_start() at the top of the page - another one is line 57
if ($_SESSION['logoclub']){

Open in new window


You might want to change this to
if (isset($_SESSION['logoclub'])){

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi"

Dosent help :(
Tryed:

error_reporting(E_ALL);

On the php file, but get noe PHP errors..

And have only one instance of the same browser.

Hmmm, this is very strange
Can you describe how they "get changed" - some examples?
Have a Form, that i fill out with some data.

Before i hit save button, this session -> $_SESSION['logoclub'] = 14

After i hit save button, it change this vale to the value from a listbox
example : $_SESSION['logoclub'] = 10
Looks like it is time to strip out all of the irrelevant stuff and distill the problem down to the SSCCE.  Then we can begin adding things back into the script until we find the error.
You are not showing us all the code - $_SESSION['logoclub']  is never on the left of an '=' so the assignment is happening elsewhere.

Your code has some files that are included (newsletter, auth, etc) I suggest we have a look at those to find out where the assignment is taking place.
Hi!

Include the file that set the session -> ogoclub

<?php

session_start();

if(isset($_REQUEST['logout'])){
	unset($_SESSION['_newsletter_loggedin']);
	$newsletter->logout();
	header("Location: index.php");
	exit;
}


$login_status = (isset($_SESSION['_newsletter_loggedin']) && $_SESSION['_newsletter_loggedin']);

if(isset($_REQUEST['username']) && isset($_REQUEST['password'])){
  	
	$login_status = $newsletter->login_admin($db,$_REQUEST['username'],$_REQUEST['password'],$_REQUEST['mem_golfclub']);
    $namegolf = $newsletter->get_golfclubname($db,$_REQUEST['mem_golfclub']);

}

if($login_status){
	// support for multiple logins at one time.
	$_SESSION['_newsletter_loggedin'] = $login_status;
	if(isset($_REQUEST['username']))
	{$_SESSION['user_logged_in'] = $_REQUEST['username'];}
	if(isset($_REQUEST['mem_golfclub']))
	{$_SESSION['logoclub'] = $_REQUEST['mem_golfclub'];}

}
else{
  $error = '<div class="newsletter_error"> Du har ingen tilgang </div>';
}


if(!$login_status){
	?>
	<html>
	<head>
		<title>Login</title>
		<link rel="stylesheet" href="layout/css/styles.css" type="text/css" />
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	</head>

	<body>
	<div id="wrapper" style="width: 900px; margin: auto;">
	<h1>Nyhetsbrev Dashboard</h1>
	<?php if(isset($error)) { echo $error; }?>
	<fieldset class="two_col left_col" style="width: 30%;">
		<legend> Nyhetsbrev administrator </legend>
		<form action="" method="post">
			
			
			<label>Din Golf Klub bbb</label>
				<div class="form_field"><select name="mem_golfclub" id="golfclub">
					<?php 
					
					$newsletters = $newsletter->get_golfclubs($db);
					
					foreach($newsletters as $newsletter){
						?>
						<option value="<?php echo $newsletter['golf_id'];?>"><?php echo $newsletter['namegolf'];?></option>
						<?php
					}
					?>
					
				</select>
				</div>	
			
			
			<label>Brukernavn</label>
			<div class="form_field">
				<input type="text" name="username" value="<?php echo (_DEMO_MODE)?$newsletter->settings['username']:'';?>">
			</div>
			
			<label>Passord</label>
			<div class="form_field">
				<input type="password" name="password" value="<?php echo (_DEMO_MODE)?$newsletter->settings['password']:'';?>">
			</div>
			<br />
			<input type="submit" name="login_button" value="Login" class="button">
		</form>
	</fieldset><!-- end two_col -->
	
	<fieldset class="two_col right_col">
		<legend> Softkey's newsletters </legend>
		<label class="next_label">Support Softkey AS ?</label>
		<div class="single_info grid_2">
			<label class="inline_label">Support</label>
			<p> Ta kontakt hvis du står fast med noe
			    <a href="mailto:youremailaddress">support@softkey.no</a>  </p>
		</div>
		<div class="single_info grid_3">
			<label class="inline_label">Lage Nyhetsbrev</label>
			<p>Vi kan hjelpe deg og lage nyhetsbrev.</p>
		</div>

		<div class="single_info grid_2">
			<label class="inline_label">Import av gjester</label>
			<p>Lage mail lister for dine kunder</p>
		</div>

		<div class="single_info grid_3">
			<label class="inline_label">Bli en smart bruker</label>
			<p>Subscribe to get these awesome scripts <a href="http://www.thetutlage.com/subscribe"> xxx</a></p>
		</div>
	</fieldset>


	</div>
	</body>
	</html>
	<?php 
	exit;
}

Open in new window

I have to give up on this question.  

There is a logic error that is mutating the $_SESSION in an unexpected way (we know that).  But the way this code is written, we cannot write any automated tests that will detect the error condition, and there is not enough time left in life to keep asking over and over for a complete code set - we're getting code fragments when what we really needed was the complete code set.  And even if we get that, the logic is so convoluted that we may not be able to figure out where the session is getting changed.  

So I'll just leave it with my earlier suggestion: Discard this code entirely and redesign it from the ground up.  That will be your quickest path to a working application.

Sorry I can't help.  Best of luck with the project, ~Ray
tHANKS