0

What I am trying to do:

When a user hits the index.php page (the start of a couple pages of forms), I need any existing session to be destroyed and a new one to start. This is so that old session variables are not reused in the new process.

What I have done:

I believe this should check if a session already exists, if it does, destroy it and start a new one. (Need to use session_id() for the check)

if(session_id() == '') {
    session_start();
}else{
    session_destroy();
    session_start();
}

The issue:

The previous session variables are still set and causing issues with the process.

Am I missing something in the way to reset all session varibles?

meager
  • 209,754
  • 38
  • 307
  • 315
MRC
  • 535
  • 2
  • 10
  • 27
  • 1
    See http://stackoverflow.com/questions/6249707/check-if-php-session-has-already-started for a PHP >= 5.4.0 way to check for active sessions. The version you are using will detect active sessions for PHP < 5.4.0. – George Cummins Sep 24 '14 at 14:45
  • @GeorgeCummins Thanks George. I used that originally which worked, but the issue is our client is using an older version. Since I used the answer there to change it to the other older PHP version method, it doesn't work. – MRC Sep 24 '14 at 14:47
  • @GeorgeCummins Also not to sound rude, but that's why I wrote" (Need to use session_id() for the check)" in the question. – MRC Sep 24 '14 at 14:50

1 Answers1

0

In documentation you can read:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. session_destroy();

So you have to do following things:

$_SESSION = array(); //empty session variable 
$cookieParams = session_get_cookie_params();
setcookie(
    session_name(), 
    '', 
    0, 
    $cookieParams['path'], 
    $cookieParams['domain'], 
    $cookieParams['secure'], 
    $cookieParams['httponly']
);
session_destroy(); //and now you can call your function
Kasyx
  • 3,082
  • 18
  • 29
  • Ah, I had assumed that "destroys all of the data associated with the current session" meant it unset everything. Thanks. I have now changed it to set the variable to 0 or 1 depending if the action has already been carried out. – MRC Sep 24 '14 at 14:48