nemo has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys, I've been trying to write simple login/logout scripts with CGI::Sessions but I'm not having much luck. So everything compiles and runs ok (using strict etc) but not quite as I expected. Here is my sample code:
sub loadSession($$){ my ($dbhandle,$cgi) = @_; my $session = CGI::Session->load("driver:MySQL", $cgi, {Handle=>$d +bhandle}); if ( $session->is_expired && $session->param("logged_in")) { displayLoginPage("Your session has expired, please log in agai +n"); exit(0); }elsif ( $session->is_empty) { $session = $session->new("driver:MySQL", $cgi, {Handle=>$dbhan +dle}); $session->expire('+1m'); print $session->header(); displayLoginPage(undef); exit(0); }else{ print $session->header(); } return $session; } sub logout($$){ my($cgi,$dbhandler) = @_; my $session = CGI::Session->load("driver:MySQL", $cgi, {Handle=>$d +bhandler}) or die CGI::Session->errstr; $session->clear(); $session->delete(); }
So the session expires but isn't marked as expired. As in the elsif branch for the empty session is executed not the expired branch. Also when I attempt to logout of the session the session id still seems to be valid. A new session id is not generated (I print them out on each page) for the login page. Can anyone point out the flaws in my logic? I've been through the cpan tutorial but I still amn't getting this.

Replies are listed 'Best First'.
Re: Problems with CGI Sessions
by moritz (Cardinal) on Dec 02, 2007 at 14:45 UTC
    You should call $session->flush() after you stored some values (including expiry times).

    BTW there's no need to create a new session in the elsif branch.

Re: Problems with CGI Sessions
by fenLisesi (Priest) on Dec 02, 2007 at 14:54 UTC
    The second condition in $s->is_expired && $s->param("logged_in") looks suspicious. Would it be possible for you to use new and not bother with load? new should be able to handle all of these. You can check for your $s->param("logged_in") on whatever session new gives you, either loaded from an old stored copy, or a newly minted one.