Link to home
Start Free TrialLog in
Avatar of pnoeric
pnoericFlag for United States of America

asked on

Switching sessions mid-stream

I have an app that stores the user's IP and useragent with the session... then also stores the session ID in the database.

Every time a page is accessed, I check the current session against the one in the DB. If they're differerent, voila, I can tell the account is logged in from two different computers at the same time.

What I'm trying to do now is switch over to the canned session and fetch the old IP and useragent so I can log them. My code is as follows:


$oldsess = (fetched from user record in db)
$newsess = session_id();

if ($oldsess != $newsess) {

      session_id($oldsess);            // switch to the one we found in the db
      session_start();
      $oldIP = $_SESSION['ip'];
      $oldUserAgent = $_SESSION['useragent'];
      
      session_id($newsess);            // switch back to the current one
      session_start();
      $newIP = $_SESSION['ip'];
      $newUserAgent = $_SESSION['useragent'];

The problem is that it's not really 'switching' sessions when I try to go to the old one-- at the end of the code above, $oldIP == $newIP and $oldUserAgent == $newUserAgent.

Why is this failing? Does switching sessions require a page refresh (so http headers are sent), or something like that?

E

p.s. I'm trying to avoid storing the IP address in the db, though that would be a different way to solve this.
Avatar of jkna_gunn
jkna_gunn

does session_id not need to be called before session_start??, so when you try to switch back it fails.
Avatar of pnoeric

ASKER

eh? not sure I follow. session_id sets the session, then session_start "kicks it into place." or so I believe that's how it works. or are you saying try it without the session_start after switching it with the _id?
ASKER CERTIFIED SOLUTION
Avatar of jkna_gunn
jkna_gunn

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
Avatar of pnoeric

ASKER

Ugh. I tried it-- then I get "Session object destruction failed" on the line with session_destroy

Very, very strange. Any other ideas? I can't tell if the problem is that sessions are buggy or the documentation is just really fuzzy.

best
Eric
Avatar of pnoeric

ASKER

Never was able to really get this working :-( Sesssions seem to either be broken in PHP or not documented well enough that I could figure out how to switch 'em in mid-stream. I ended up just storing the IP address and running with that.

I'm crediting jkna_gunn the points since s/he tried to help me out :-)

best
Eric