How to end sessions without cookies.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
arvaker
Forum Newbie
Posts: 1
Joined: Mon Dec 11, 2006 4:09 am

How to end sessions without cookies.

Post 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
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post 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();
Post Reply