Page 1 of 1

How to end sessions without cookies.

Posted: Mon Dec 11, 2006 5:26 am
by arvaker
Hello, I would like to know how I can finalize a session that works without cookies. By now I do it with session_destroy () that doesn't end the session but leaves it without effect, although the ID of the session continues existing (in the page where I execute session_destroy () it lost the ID, but in the previous ones not). I have tried with session_write_close () but does not work (in addition I don't keep variables in databases).

I also wanted to know how to finalize the session in case the user does not indicate explicitly that he leaves the session. I mean, if someone directly changes of page or closes the browser.

Can I give a time of expiry to a session which does not use cookies?

Thanks in advance,

Álvaro

Posted: Mon Dec 11, 2006 5:37 am
by aaronhall
Proper way to close a session:

Code: Select all

session_start();

// unset the session variables
$_SESSION = array();

// unset the session cookie if it exists
if (isset($_COOKIE[session_name()])) {
   setcookie(session_name(), '', time()-42000, '/');
}

session_destroy();
A session cookie will normally be destroyed by the browser as soon as the browser closes. There is no reliable way to detect when the user has left the page. You could use something like this at the top of your page to destroy the session if the user has been idle for a certain amount of time:

Code: Select all

session_start();

// check that the user has not been idle for longer than 10 minutes (60*10)
if($_SESSION['last_pageload'] < (time() - (60*10))) {
  // destroy the session and redirect to login page
}

// set $_SESSION['last_pageload'] to the current time
$_SESSION['last_pageload'] = time();