http://www.perlmonks.org?node_id=968308

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

I am trying to implement a simple login dialog for my application, and am having trouble making it work.

Below is a small piece of code that illustrates my problem:

#!C:/Perl/bin/perl use strict; use warnings; use CGI::Carp qw( fatalsToBrowser ); use CGI; use CGI::Session; run(); sub run { my $cgi = new CGI(); my $action = $cgi->param('do'); # # Create a session object # my $session = undef; if ($action eq 'login') { # Create a brand new session, by passing an undef cgi argument + to CGI::Session. $session = new CGI::Session("driver:File", undef, {Directory=> +"/"}); } elsif ($action eq 'stay_logged') { # Keep the existing session, by passing the CGI object to CGI: +:Session. $session = new CGI::Session("driver:File", $cgi, {Directory=>" +/"}); } else { die "Invalid action '$action'\n"; } # # Send the CGISESSID cookie to the browser # my $cookie = undef; my $session_id = undef; if ($session) { $session_id = $session->id(); $cookie = $cgi->cookie(CGISESSID => $session_id); print $cgi->header(-cookie=>$cookie); } print $cgi->start_html('Fooling around with session login/logout') +; print "<h3>\$action='$action'</h3>\n"; print "<pre>\$session_id=$session_id\n</pre>\n\n"; print "<pre>\$cookie=$cookie\n\n</pre>\n"; my $random_id = rand(); print "<ul>\n"; print " <li><a href=\"try_logon.cgi?do=login&rand=$random_id\">l +ogin</a></li>\n"; print " <li><a href=\"try_logon.cgi?do=stay_logged&rand=$random_ +id\">stay logged</a></li>\n"; print "</ul>\n"; print $cgi->end_html; }

This script displays a 'login' and a 'stay logged' links. The 'login' link is supposed to create a brand new session (line 21), by invoking new CGI::Session::new() and passing it an undefined value for the CGI argument. The 'stay logged' link is supposed to create a session using the current session ID (line 24), by passing an actual CGI instance as the second argument of CGI::Session::new().

But it doesn't work!

If I click multiple times on the 'login' dialog, I see the same session id being used over and over again. Same goes for the 'stay logged' link, but that one is to be expected.

Note that I am running under mod_cgi (NOT mod_perl), and that it can't be a cache issue, because the URL of each of the invocations of the script is different (because I add a different random cgi argument to it everytime).

What am I doing wrong? Thx.