I’m having a difficult time with PHP doing some very basic session security type of things:
- A new session ID should be generated when switching from a non-authenticated context to an authenticated one
- A new session ID should be generated when switching from an authenticated context to a non-authenticated one
What I’d like to do is not only regenerate a session ID when switching contexts, but also immediately put something into the session (such as a FLASH) when switching those contexts. These three pages should hopefully clarify my expectations:
<?php
/* page1.php */
session_start();
# Just putting something in the session which I expect to
# not show up later
$_SESSION['INFO1'] = 'INFO1';
?>
<html>
<a href="page2.php">Page 2</a>
<?php print_r($_SESSION) ?>
</html>
So when this page is displayed, I expect to see INFO1 show up. I also expect when I come back here NOT to see INFO2 show up. If I don’t already have a session ID, I expect to get one (I do).
<?php
# page2.php
session_destroy();
session_regenerate_id(TRUE);
$_SESSION['INFO2'] = 'From page 2';
session_write_close();
header('Location: page3.php');
exit;
?>
This would be most akin to a logout function – we invalidate the existing session by passing TRUE to session_regenerate_id. Also, I put something in the (presumably) new session – which may be like a FLASH – say “You’ve been logged out successfully.
#page3.php
<html>
<body>
<?php session_start(); ?>
<?php print_r($_SESSION); ?>
</body>
</html>
On this page, I’d expect two things to happen:
- The redirect from
page2.phpshould have sent me a new session ID cookie (it did not) - I’d expect for the
print_rto print information fromINFO2, and not fromINFO1. It doesn’t have information fromINFO1, but does not include information fromINFO2.
I’ve had very, very inconsistent results with session_regenerate_id and redirects. It seems like such a kludge to manually send that Set-Cookie header – but even if I didn’t, session_regenerate_id(TRUE) should invalidate the old session ID anyhow – so even if the browser didn’t for some reason get the new session ID, it wouldn’t see any information in the session because the old session had been invalidated.
Has anybody else had experience with these sorts of issues? Is there a good way to work around these issues?
Based on the documentation for
session_regenerate_id, it sounds like the contents of the session are always preserved. You’re passing it aTRUEargument, but that only deletes the actual session file on disk; the values stored in it are kept in$_SESSIONand then written to the new session.So perhaps wipe it out manually:
Not sure why you aren’t seeing the new cookie, though. Where did you check, what did you see?
edit: The problem, as revealed by the OP in a comment below, appears to be that page2 never called
session_startto load the first session. Which produces the following:I have no idea if this is minimal. Figuring out how much of it can be deleted is left as an exercise to the reader.