title: PHP session regeneration security
body: <p>I'm having a difficult time with PHP doing some very basic session security type of things:</p>
  
  <ul>
  <li>A new session ID should be generated when switching from a non-authenticated context to an   authenticated one</li>
  <li>A new session ID should be generated when switching from an authenticated context to a non-authenticated one</li>
  </ul>
  
  <p>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:</p>
  
  <pre><code>&lt;?php
  /* page1.php */
  session_start();
  # Just putting something in the session which I expect to
  # not show up later
  $_SESSION['INFO1'] = 'INFO1';
  ?&gt;
  &lt;html&gt;
  &lt;a href="page2.php"&gt;Page 2&lt;/a&gt;
  &lt;?php print_r($_SESSION) ?&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>So when this page is displayed, I expect to see <code>INFO1</code> show up. I also expect when I come back here NOT to see <code>INFO2</code> show up. If I don't already have a session ID, I expect to get one (I do).</p>
  
  <pre><code>&lt;?php
  # page2.php
  session_destroy();
  session_regenerate_id(TRUE);
  $_SESSION['INFO2'] = 'From page 2';
  session_write_close();
  header('Location: page3.php');
  exit;
  ?&gt;
  </code></pre>
  
  <p>This would be most akin to a logout function - we invalidate the existing session by passing <code>TRUE</code> to <code>session_regenerate_id</code>. Also, I put something in the (presumably) <strong>new</strong> session - which may be like a FLASH - say "You've been logged out successfully.</p>
  
  <pre><code>#page3.php
  &lt;html&gt;
  &lt;body&gt;
  &lt;?php session_start(); ?&gt;
  &lt;?php print_r($_SESSION); ?&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>On this page, I'd <strong>expect</strong> two things to happen:</p>
  
  <ul>
  <li>The redirect from <code>page2.php</code> should have sent me a new session ID cookie (it did not)</li>
  <li>I'd expect for the <code>print_r</code> to print information from <code>INFO2</code>, and <strong>not</strong> from <code>INFO1</code>. It doesn't have information from <code>INFO1</code>, but does not include information from <code>INFO2</code>.</li>
  </ul>
  
  <p>I've had very, very inconsistent results with <code>session_regenerate_id</code> and redirects. It seems like such a kludge to manually send that <code>Set-Cookie</code> header - but even if I didn't, <code>session_regenerate_id(TRUE)</code> 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.</p>
  
  <p>Has anybody else had experience with these sorts of issues? Is there a good way to work around these issues?</p>