Page 1 of 1

Session Cookie Expiry? [ Solved ]

Posted: Wed Jul 19, 2006 11:02 am
by WorldCom
I'm trying to use the session cookie with an expiry but keeps the user logged in if they are viewing pages. I've searched here and can't really find any thing.

login.php

Code: Select all

// after checking login infomation I set the cookie params .... I know its only 2 mins 

        session_set_cookie_params( 120 );
	session_start();
	$_SESSION[username] = $username;
	$_SESSION[password] = $password;
	$_SESSION[user_agent] = md5($_SERVER['HTTP_USER_AGENT']);
Then my header for all pages:

Code: Select all

<?php
session_set_cookie_params( 120 );
session_start();
require('connect.php');
if(!isset($_SESSION['username']) | !isset($_SESSION['password'])) {
	mysql_close();
	header("Location: http://path.to.site/logout.php?id='Expired'");
	exit();
	}
if($_SESSION[user_agent] != md5($_SERVER['HTTP_USER_AGENT'])) {
	mysql_close();
	header("Location: http://path.to.site/logout.php");
	exit();
	}
NOTE: When I first tried this, it did not log me out at all. I checked cookies on my machine and found that the PHPSESSID cookie was still set. Now I make sure I destroy it on logout. One thing I did notice, was when I was logged out before I destroyed it, the cookie was updated with a new time. Like it expired, logged me out, then it got reset.??

OK, this does log out after 2 mins but does not reset the cookie on each page view. Is this the correct way?

I tried something else like just setting my own cookie but still can't change it. Would I have to destroy the cookie on each page and reset it?

Still fairly new at this.

Edit: Ok I took out the destoy cookie part in logout. When I did get logged out, it did reset or create a new cookie with the 2mins. Then I log back in, that cookie is still set. Its like I'm not doing something in the right order.
---------
Solved: Got it solved. Here's what I didn't understand. I thought that using:

Code: Select all

session_set_cookie_params( 120 );
on every page, eg header.php, would refresh the PHPSESSID cookie. Well it doesn't. You would have to write over it like any other cookie:

Code: Select all

setcookie('PHPSESSID', '', time()+120, '/', '', 0);
Adds another 2 mins.
Also, I see that if you don't destoy this cookie and don't close your browser down, it will not reset the time upon session_start(). So you would have to update it with setcookie.

I hope that is right :)