Sunday, August 22, 2010

PHP never expire vs timeout cookies vs sessions

As mentioned earlier I have a newly found hobby with PHP MySQL programming, and after lots of trial and error in the development of this project I found a working method for a 'remember me' button and the expiring cookies and sessions.

The first part is login script, here you will determine if they want to be remembered in our terms this means to never time out the user. This is done with simple cookie to set the expiration a week from now, here is my code:

$long=time()+60*60*24*7; //Setting up the expiration time
$short=time()+60*25; //short time (25 minutes) for those without 'rememberme'
$username = $params['username'];
//Check whether the remember me box is checked
if (isset($params['rememberme']) && $params['rememberme'] == "on"){
setcookie('username',$username,$long); //username cookie and long expiration
setcookie('expire','no',$long); //expire is set to no
setcookie('expire','yes',$short); //expire is set to no
setcookie('username',$username,$long); //username cookie with short expiration

Easy right?
Next setting the users that will be timed out after inactivity I decided 25 minutes are enough because it is also the time default sessions get timed out.
Notice that the username cookie is still with a long expiration, the expire cookie is in control of expiration and the username just saves the username data which is required in various places to determine access and such.

After the login page you will need a function that is called every time something is requested, (in order not to annoy the users and only time out after inactivity) this can look something like this:

function check_login(){
if ($_COOKIE['expire'] == "no"){
$_SESSION['user'] = userInfo($_COOKIE['username']); //reset the session
}elseif ($_COOKIE['expire'] == "yes"){
setcookie('expire','yes',time()+60*25); //reset the cookie time
$_SESSION['user'] = userInfo($_COOKIE['username']); //and session
echo " Session timed out. To login  input type=\"button\" value=\"Reload Page\" onClick=\"window.location.reload()\"";     //use the tag opening before input, blogger messes here lol

More coming soon...

No comments: