Артем (al1us) wrote in perl,
Артем
al1us
perl

CGI::Session

Hey,

I can't understand how sessions work in perl. I have read the manual on cpan but still can't get sessions to work.

When a user comes for the first time, he sees a login page. Enters his credentials in the form and the is redirected to the same login page where the script controls the username and password and if everything is ok, then the user is redirected to another page or in case of any problems the user sees the login form again.

On the login page I first create a session, then check whether the user is logged in or not and decide what to do next:
my $cgi = CGI->new();
my $session = new CGI::Session(undef, $cgi, {Directory=>"/tmp"});
if ($logged) { &redirect(); }
else {
    ... routines that check username and password ...
    ... if the username and pass are correct, then write some params, send cookie and redirect ...
    $session->expire("+15m");
    $session->param("logged", 1);
    my $cookie = $cgi->cookie(CGISESSID => $session->id);
    print $cgi->header( -cookie => $cookie);
    &redirect();

This code seems to work, because I am being redirected to the proper page after submitting the login and password. On every other page I check whether the user is logged in or not and if not, then redirect him to the login page
my $cgi = CGI->new();
my $session = new CGI::Session(undef, $cgi, {Directory=>"/tmp"});
if ($logged != 1) { &redirect(); }
else { ... }

But every time I am being redirected to the login page. I looked in the /tmp and found 4 session files, 1 has "logged" parameter set and 3 sessions without "logged" being set. The first session is created when the user comes for the first time. The second one, as I understood, is created when the user submits his credentials. During this time the "logged" parameter is set. The third is created when I am redirected to another page (but why doesn't it pick already created session?) and the fourth when I am redirected back to the login page.
I also tried to create sessions like it is described in cpan:
my $sid = $cgi->cookie("CGISESSID") || undef;
my $session = new CGI::Session(undef, $sid, {Directory=>"/tmp"});

But has the same result. Tried to pass the session id with the URL. Didn't help.
Any ideas?
Thanks in advance

UPD: fixed. Passed the session id via URL and it worked. Guess, there is something wrong with my browser not receiving cookies
Subscribe
  • Post a new comment

    Error

    default userpic
  • 11 comments