Link to home
Start Free TrialLog in
Avatar of bliesveld
bliesveld

asked on

How do I change an Active Session Variable "AKA LIVE VARIABLE"?

Ok, so I have a membership site.  When a user logins in I register several variables including email, name, address, etc.  Now I want to create a update profile section, when I update my DB everything works fine, now I need to update the session variables so the data in my members only area will update.  How would I go about doing this? Ending the Session?
Avatar of arantius
arantius

bliesveld,

What does "when I update my DB everything works fine" mean?  This means you edit the data stoerd in the database?

You want to be able to do that while a user is logged in and have it also change their session?  I don't think that's going to happen, if so.
There shouldn't be a need to end the session, just reassign the session variables before any data is outputted.

For example, presumably you will have an update form using the post method, you could then just do

$_SESSION['username'] = $_POST['username'];

etc

OR validate the data first, update the database, then re-assign the value to the new session var, eg:

$new_username = $_POST['username'];
//validate username
//run an update query

$_SESSION['username'] = $new_username;

Or a less efficient method, update the database based on the form information, then requery it for the new data and assign the results to your session variables.

As i said above, make sure you do this before any output so that anything that is dependant on the session variables will show the new settings/values and will not be out of date with the previous values.
Where you issue the update in your database, also update the settings in the SESSION like

if (mysql_query('UPDATE table Set email= ...')) {
  $_SESSION['email'] = $_POST['email'];
 ...
}

If you are talking about updating the settings of another user in the DB then you will also need to implment a check if the values for that user have been changed in the database and update the settings in his session

$res = mysql_query('SELECT * from usertable WHERE user=\'{$_SESSION["userid"]}\' AND EditTime> {$_SESSION["EditTime"]}');
$row = mysql_fetch_assoc($res);
if (!empty($row['EditTime'])) {
  $_SESSION['email'] = $_POST['email'];
 ...
}

Note: remember you must have session_start(); at the top of every page to initialize the session data.

Think of a session variable like you would a normal variable only with a super global scope.

eg, normally you would do:

$var = "some value";
//but now you need to give it a different value
$var = "new value";

echo $var; //outputs new value

session variables can be used just the same

$_SESSION['variable'] = "some value";
$_SESSION['variable'] = "now equals this value";

You just reassign the value.
Avatar of bliesveld

ASKER

ok, here is what I have been trying?
      
// Get data from form

                $username = $_POST['username'];
      $business_name = $_POST['business_name'];
      $first_name = $_POST['first_name'];
      $nast_name = $_POST['last_name'];
      $Password_Question_Answer = $_POST['Password_Question_Answer'];

// set retrun path
      
      $FORM_PATH = ROOT_PATH."/MembersArea/update.php";

************************************************
A bunch of error checking I left out of this example
************************************************

// Update DB

$update_basic_info = mysql_query("UPDATE core SET business_name = '$business_name', first_name = '$first_name', last_name = '$last_name', Password_Question_Answer = '$Password_Question_Answer'    WHERE username = '$username'") or die(mysql_error());
                  
      if(!$update_basic_info)
      {
            $form_error = "There was an error updating your info.";
            include $FORM_PATH;
            exit();
      }
      else
      {
      
            // Update session variables!
            
            session_start();

            $_SESSION['first_name'] = $first_name;
            $_SESSION['last_name'] = $last_name;
            $_SESSION['business_name'] = $business_name;
            $_SESSION['Password_Question_Answer']= $Password_Question_Answer;
            
            
            $form_error = "Info Updated.";
            include $FORM_PATH;
            exit();

      }

This seems like what you are suggesting, and the way I had tried to implement it but It is not working for me...  It seems like I need to refresh the Session or somthing?

Can you elaborate on "it is not working"...

Are the old session values remaining or is there an error?

Its usually one of two things.

1) code flow. You output data before you have made the changes to the session variables
2) session_start(); is placed after output so the session data isn't initialized (you may want to move this to the very top of your script either way).
Sorry, poor choice of words....  there is no error, yes the session variables remaining the same is my problem... Everything is working except the session variables will not change until i logout and log back in.  

I dont output any data until the -> include $FORM_PATH; call.

The info sent to the DB update fine.  its the $_SESSION['CALL'S] on  "MembersArea/update.php" or $FORM_PATH that are not updating.
I don't see anything wrong with what you have posted above.

You might want to try adding
error_reporting(E_ALL);
to the top of the script to see if there are any errors causing this.

Failing that could we see the contents of update.php? It might be that the old session variables are being assigned again due to an unrestricted conditional or something.
ok I get this error using: error_reporting(E_ALL);  -> neat trick by the way....


Notice: A session had already been started - ignoring session_start() in /home/p2pmlmco/public_html/includes/gatekeeper.php on line 2

gatekeeper.php is the script I incluede to protect my Members only pages and looks like this:

<?php
      session_start();
      include_once '/home/p2pmlmco/public_html/includes/config.php';
      
      if(!isset($_SESSION['first_name']))
                {
                  header('Location://www.p2pmlm.com/bad_login.php');
                  exit();
      }
?>
That error just means you don't need session_start(); in your include file (only needs to be declared once) but is not anything to do with the problem.

Is there anything in config.php that alters the session values? I would have guessed not but i can't see anything that would cause the change.

Lets do a bit of debugging.

Immediately after you set your session values (ie. just after $_SESSION['Password_Question_Answer']= $Password_Question_Answer;) add:

print_r($_SESSION);

That will give you a human friendly output of the session array contents... you should see the new values along with the corresponding array keys.

Add that same line again somewhere near the end of your script, the values should output as the newly assigned values still, if they output the old values you should be able to use this to narrow down where in your script the problem is being caused.
They are all still the same?

There is no session data in the config file.

Here is what my main.php looks like:

Main.php
*******************************************************

<?php
            include_once '/home/p2pmlmco/public_html/includes/config.php';
            include ROOT_PATH.'/includes/gatekeeper.php';
            include ROOT_PATH.'/includes/dateOrder.php';


?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<title>P2PMLM.COM</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
<!--
      // style page link
</style>


</head>

<body>

      
      <div id="CONTENT">
      
            <div id="LOGO"><img src="<?php echo WEB_PATH.'/Images/top_bar.jpg'?>" width="700" height="9"></div>
            <div id="TOPBAR"><img src="<?php echo WEB_PATH.'/Images/logo.jpg'?>" width="98" height="10"></div>
            <div id="REF">
                    <div align="right" class="BLUE"><a href="<?php echo WEB_PATH.'/includes/logout.php'?>">LOGOUT</a></div>
             </div>
              <div id="MAIN_IMAGE"><img src="<?php echo WEB_PATH.'/Images/main_image.jpg'?>" width="484" height="197"></div>
                                  <div id="RIGHTBAR">
                             <p>
                                             <?php include "components/cinfo.php"?><?php include "components/cstats.php"?><?php include "components/ctoolbar.php"?>
                                               </p>
                            <p>&nbsp;</p>
                                           </div>
            <div id="MAIN_CONTENT">
             <p>
                <?php include "components/cmain.php"?>
             </p>
        </div>

      </div>
      
</body>

</html>


cstats.php - this uses some session variables in a toolbar.
*******************************************************

  <table width="100%" border="0" cellspacing="2" cellpadding="2">
    <tr>
      <td><div align="left"><img src="<?php echo WEB_PATH.'/Images/member_info.jpg'?>" width="98" height="17"></div></td>
    </tr>
    <tr>
      <td><span class="style55"><?php echo $_SESSION['username'];?></span></td>
    </tr>
    <tr>
      <td><span class="style55"><?php echo $_SESSION['business_name'];?></span></td>
    </tr>
    <tr>
      <td><span class="style55"><?php echo $_SESSION['first_name'].' '.$_SESSION['last_name']; ?></span></td>
    </tr>
    <tr>
      <td><span class="style55"><?php echo $_SESSION['email_address'];?></span></td>
    </tr>
    <tr>
      <td><span class="style55">Last Login: <?php echo DateOrder($_SESSION['last_sign_in'])?></span></td>
    </tr>
    <tr>
      <td><div align="left" class="style7"></div></td>
    </tr>
    <tr>
      <td><div align="right">
        <a href="<?php  echo WEB_PATH.'/MembersArea/update.php'?>"><img src="<?php  echo WEB_PATH.'/Images/update_info.jpg'?>" width="98" height="17" border="0"></a>
      </div></td>
    </tr>
  </table>
 
hmm, if the old values are still being shown directly after assigning the new ones and there are no errors, the only thing i can think of that would cause behaviour like this is register globals, although even that doesn't seem likely here. Its a shot in the dark but all i can think of at the moment.

You either need to set register_globals to off in your php.ini file (and then restart your webserver) or
add: ini_set("register_globals", 0);  to the top of your script. They should (and may well be) off anyway for security reasons.

I will take another look through your code in the morning with fresh eyes, unless anyone else can spot the problem in the mean time.
I suggest you not to store user data in session variables. The only thing you need to store in session is user ID. Then you can retrieve user data at authorization stage and this way always be sure that user data are up to date.
I believe, you already have some code that is executed in the beginning of every member area page. This code is checking if user is logged in and it can retrieve user data at the same time.
Use something like this:
$result = mysql_query("SELECT * FROM users WHERE userid='".$_SESSION['userid']."'",$db_link);
if (mysql_num_rows($result)) { // logged in
    $userData = mysql_fetch_assoc($result); // retrieve user data
    ...
} else { // not logged in
    ...
}

Then you can extract($userData) if you like to have separate variables.
Diablo84  any luck on this?  I have been look at it for a while now... i think I might have to come back to it later... everything looks good to me.
Hi bliesveld, there is not much sense behind this problem, no errors but the changes are not occuring... i am half expecting it to be something simple that is being overlooked.

I am a little busy at the moment so il put some time aside a little later to look through your code again and see if i can spot something i missed before.
thanks
<?php  echo WEB_PATH.'/MembersArea/update.php'?>

I think this was the issue... when I use

header('Location://www.p2pmlm.com/MembersArea/main.php');

everything updates...
ASKER CERTIFIED SOLUTION
Avatar of modulo
modulo

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