Page 1 of 1

how to log off a session when the browser window is closed?

Posted: Sat Sep 10, 2005 11:54 am
by leonardobii
So I created user authentication and session handling scripts, but I cant figure out how to log off a session when the browser window is closed? any suggestions?

Posted: Sat Sep 10, 2005 12:00 pm
by raghavan20
from php manual
session.cookie_lifetime integer
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params().
do more reading on, http://uk.php.net/session

Posted: Sat Sep 10, 2005 12:02 pm
by leonardobii
thanks, but would there be a way without using cookies?

Posted: Sat Sep 10, 2005 12:04 pm
by Chris Corbyn
You'd need a session timeout to acheive it well. So basically the user is logged off after X minutes of inactivity.

I guess you could use javascript with an unload event but it won't work in all cases.

Posted: Sat Sep 10, 2005 12:06 pm
by leonardobii
thanks but ive already considered all those options, but can't find anything reliable. it seems that there is no proper way of doing it.

Posted: Sat Sep 10, 2005 12:15 pm
by feyd
the only reliable way is using the lifetime, it doesn't require cookies because it's based on the last usage time of the session storage unit.

Posted: Sat Sep 10, 2005 12:18 pm
by leonardobii
thanks man, makes thing more clear.

Posted: Sat Sep 10, 2005 12:28 pm
by raghavan20
this is useful to close session after some period of inactivity.

Code: Select all

<?php
session_start();
if (!isset($_SESSION["last_access"])){
	$_SESSION["last_access"] = time();
}else{
	//echo $_SESSION["last_access"]."<br />"; //last access time
	//echo time()."<br />"; //current time
	//echo time() - $_SESSION["last_access"]."<br />"; //difference between current time and last access time
	if (time() - $_SESSION["last_access"] > 5*60){ //expire time set to five minutes
		//echo "session deleted!!!";
		session_destroy(); //destroys all session variables
		setcookie(session_name(), "", time() - 10); //destroys the session itself which is actually transported via cookie
		//unset($_COOKIE[session_name()]); //this also could be used to destroy the session cookie; alternative for the former
	}
}
?>

Posted: Sat Sep 10, 2005 12:39 pm
by feyd
or you can just ask PHP to handle it automatically. The following are directives you can toggle anywhere you like (.htaccess, php.ini, your script)
session.gc_divisor
session.gc_maxlifetime
session.gc_probability

Posted: Sat Sep 10, 2005 1:29 pm
by leonardobii
sorry, was lunchtime, im not familiar with those, could you post an example using those?

1. Where am I suppose to implement it? in what part of a page?

Posted: Sat Sep 10, 2005 1:46 pm
by feyd

Posted: Sat Sep 10, 2005 2:06 pm
by leonardobii
thanks feyd