Jabda
Jabda

Reputation: 1792

Perl CGI persistent cookies

I want the user to non have to login even if the browser was closed. My cookies are set to expire after a month.

when the user logs in sucessfully

 $session = CGI::Session->new (undef, undef, {Directory=>'tmp/'})
                                      or die CGI::Session->errstr;
                $session->param('username', $username);
                $session->expire('+1M');                
                $cookie = $cgi->cookie( -name=>$session->name, -value=>$session->id );
                print $cgi->header(-cookie=>$cookie );

They are then redirected to another page that they can access as long as they don't close the browser. This is the code in the second page:

my $cookie = $cgi->cookie('CGISESSID');
if ($cookie){
        print $cgi->header(-cookie => $cookie);
else{
       //ask them to relog in
}

I can see the sessions created in tmp/. How do I load an existing cookie after the browser is closed. How do I know which session to load based on the user/browser?

Upvotes: 3

Views: 1706

Answers (1)

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24073

As long as you set a future expiration date on your cookies, they should persist even after a user restarts their browser (as long as they restart before that date, of course). To load the cookie, do exactly what you're doing:

my $cookie = $cgi->cookie('CGISESSID');

To try to load an existing session using the cookie you can simply pass your CGI object to the new method of CGI::Session:

my $session = new CGI::Session(undef, $cgi, {Directory=>"/tmp"});

This will attempt to initialize an existing session using the cookie passed in with the CGI request; if one doesn't exist, it will create a new session. Note that this assumes the cookie name is CGISESSID. To use another name, run:

CGI::Session->name("MY_SID");
# or
$session->name("MY_SID");

$session = new CGI::Session(undef, $cgi, {Directory=>'/tmp'});

If you haven't already, I would recommend reading through the CGI::Session tutorial.


EDIT: The session was set to expire in one month

$session->expire('+1M');

but the cookie was not. If you don't set an expiration on a cookie, the browser will store it in memory but not on disk; as soon as you close the browser, the cookie disappears. To set the cookie expiration, do something like

$cookie = $cgi->cookie( -name=>$session->name, -value=>$session->id, -expires=>'+1M' );

Upvotes: 3

Related Questions