msrDigit
msrDigit

Reputation: 50

cgi sessions between two Perl scripts

im using two Perl Scripts in my Website. I got a search field on the side, which invokes the first Script, the result is written in a output File. With the next click, the user invokes the second Script, this one reads the output file and builds a config File based on the user search. At the moment im only writing on output file, but i need to personalise this file with a session id.

Im trying this with CGI::Session, but I don’t understand how to to this, with these two Perl Scripts. I think i need to compare the session ids, and write a output File for every Session.

Does one of you know how to do this??

First Script: Im Writing the Session in a file:

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

Then sending a cookie to the client:

my $cookie = $cgi->cookie(CGISESSID => $session->id );

Second Script: try to get the Session ID:

$sid = $cgi->cookie("CGISESSID") || undef;
print $sid 

It gives a Status: 500.

Upvotes: 0

Views: 1094

Answers (1)

ikegami
ikegami

Reputation: 386501

You need to pass the session id to the client in a way that the client will provide it back to you in later requests. This is usually done using cookies.

use utf8;
use open ':std', ':encoding(UTF-8)';

use CGI          qw( -utf8 );
use CGI::Session qw( );

use constant SESSION_DIR    => '...';
use constant SESSION_EXPIRE => '+12h';  # From last use (not creation)

my $cgi = CGI->new();

my $session = CGI::Session->new(
   'driver:file',
   scalar($cgi->cookie('session_id')),
   { Directory => SESSION_DIR },
);
$session->expire(SESSION_EXPIRE);

# Whatever your page does
my $count = $session->param('count');
++$count;
$session->param(count => $count);
my $content = "This is request $count";

print
   $cgi->header(
      -type    => 'text/html',
      -charset => 'UTF-8',
      -cookie => $cgi->cookie(
         -name => 'session_id',
         -value => $session->id,
         -expires => SESSION_EXPIRE,
       ),
   ),
   $content;

There's only one script shown here, but there's obviously nothing stopping two scripts from accessing the same session (if they can access the same session store).

Upvotes: 2

Related Questions