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

I have some code that has been working fine - until I moved the session initialisation into one of my modules. Now the cookie is no longer being set via print->header - and so a new session is created every time I run it. Here's the (heavily pruned/edited) code:

# login.pl use CGI; use CGI::Session ( '-ip_match' ); use DBI; use MyPM qw(&open_db &close_db &getSession); use strict; use warnings; my $cgi = new CGI; my $dbh = open_db; my $session = getSession($cgi, $dbh); # Call to MyPM.pm close_db($dbh); ...... code ...... print $session->header(-type => 'application/json'); print $json; ======================================= # MyPM.pm use CGI::Session ( '-ip_match' ); our @ISA = qw(Exporter); our @EXPORT_OK = qw( open_db close_db getSession ); sub getSession { my $cgi = shift; my $dbh = shift; my $CGICOOKIE = $cgi->cookie('CGISESSID') || 'x'; my $lng = length($CGICOOKIE); if ( $lng != 32 ) print redirect( -URL => $home ); my $session = CGI::Session->new('driver:MySQL', $cgi, {Handle=>$dbh} +) ; return $session; }

If I change the call to getSession back into this:

my $session = CGI::Session->new('driver:MySQL', $cgi, {Handle=>$dbh});

It works perfectly again and the cookie is set.

Where might I be going wrong?

Replies are listed 'Best First'.
Re: CGI::Session not setting cookie
by kcott (Archbishop) on Mar 11, 2013 at 00:15 UTC

    G'day Upland,

    Welcome to the monastery.

    From your problem description and the code you posted, it looks like you're missing "use Exporter;" before "our @ISA = qw(Exporter);" in "MyPM.pm".

    I would expect that an error message like "Undefined subroutine &main::getSession called at login.pl line 13." is being generated and sent to your error log. While you can check through the logs, many find use of CGI::Carp an easier option.

    -- Ken

      Yes I do have exporter and CGI::Carp etc .. I was merely trimming the code down in the message to the bare minimum to demonstrate my problem. I said in the text that it was heavily edited/pruned.

      Thanks for the help

Re: CGI::Session not setting cookie
by Anonymous Monk on Mar 10, 2013 at 23:49 UTC
    What is this    if ( $lng != 32 ) print redirect( -URL => $home );

      Yes yes yes .. you're absolutely right! It was originally a check for the existence of the session cookie - but I then changed it to check for a cookie of 32 bytes in length - but made the mistake of ignoring the absence of cookie.

      Thanks for your help! .. and apologies for my stupidity.

        Does your issue remain, or is it solved?