PHP Regenerating session ID on login / out not wor

2019-04-13 10:49发布

问题:

I'm having trouble getting PHP's session_regenerate_id() to work in an application I'm developing. The application uses a (loose) self-made MVC framework and redirects all requests using .htaccess through the index.php file.

I'm trying to regenerate the session ID on logout but it isn't working correctly.

Here is some code from my logout controller - the expired variable is a check for session timeout:

    session_regenerate_id(true);        
    if(isset($_SESSION['expired']))
    {
        $this->registry->template->expired = true;
    }

    session_unset();
    session_destroy();

Also relevant is the code from the beginning of the index.php file:

    session_cache_expire(20);
    session_start();
    session_name("TMU");
    //session_regenerate_id();

I'm echoing out the result of session_id() at the bottom of each page to see what it contains to test if it has been regenerated.

The session ID doesn't change when you logout however. When you login again (even with another account) the session ID is the same.

You'll notice the commented out fourth line of the index.php file - if I uncomment that line the ID appears to be regenerated on every page as it should. However, when I comment the line out again the session ID is once again the original ID from before I uncommented the line in the index file...

I'm just wondering how I can get session_regenerate_id() to work. It seems like it's just not 'committing' the changed id. I've tried using session_commit() but I don't understand how it works fully and it was giving me an error when I tried to destroy the session.

PHP 5.3.10 and apache 2.2.21

回答1:

After revisiting this topic several times, I have figured it out. There were two problems.

  1. session_regenerate_id() must be called before any HTML output is displayed and/or headers are sent. (It needs to be called as one of the first functions, just like session_start()).
  2. Order matters. session_name("TMU") needs to be called BEFORE session_start() to have the desired result - I didn't catch this before.

Basically what was happening to me was calling session_name("TMU") after session_start() was causing it to set TWO session ID cookies - two sessions - one named TMU the other just the default PHPSESSID. Changing the order fixed all my problems and regenerating the ID / destroying the old session works as expected now.

For anyone having problems doing this I suggest you echo out the $_SESSION and $_COOKIE arrays to see what is happening in your particular application.