3

I need to store a login session when the user is login and remove the login session when the user has logged out of the system or the session has timeout. I am coding in Perl. I know I can use CGI::Session module in Perl but how do I make sure that the session is created by 1 cgi script and removed by another cgi script. Then all other pages of the system has to check if the session exist before it can display its contents.

Currently, I am using the following code to create a new session when the user has login successfully.

my $session = CGI::Session->new();
my $CGISESSID = $session->id();

However, how do I log the user out of the session in another cgi script? I doubt I can just use the following since the $session is not defined in the other cgi script

$session->delete();
$session->flush();

Any ideas?

4

1 回答 1

2

默认情况下,CGI::Sessions 独立于脚本。所以你应该能够做到这一点。

只是不要忘记以某种方式在客户端上保留会话 ID。它可以通过 cookie 来完成,header()例如参见 session。ID 和会话对象将被自动检索(如果保存正确)。

CGI::Session new()

如果不带任何参数调用,$dsn 默认为 driver:file;serializer:default;id:md5

CGI::Session::Driver::file

您可以将它们配置为使用您喜欢的商店和设置。


使用会话的基本示例CGI 脚本:

#!/usr/bin/perl
use strict;
use warnings;

use CGI;
use CGI::Carp qw(fatalsToBrowser); # show errors in browser
use CGI::Session;


# new query object
my $q = CGI->new();

# new session object, will get session ID from the query object
# will restore any existing session with the session ID in the query object
my $s = CGI::Session->new($q);


# print the HTTP header and set the session ID cookie
print $s->header();


# print some info

print "<pre>\n";

print "Hello!\n\n";
printf "Your session ID is: %s\n", $s->id;
printf "This sessin is: %s\n", $s->is_new ? 'NEW': 'old';
printf "Stored session 'test' value: '%s'\n", $q->escapeHTML($s->param('test'));
printf "CGI Params: %s\n", join ', ', $q->param;


# handle the form submit

if(defined $q->param('save')){
    # save param value in the session
    $s->param('test', $q->param('test'));
    printf "Set session value: '%s'\n", $q->escapeHTML($s->param('test'));
}
elsif(defined $q->param('delete')){
    # delete session
    $s->delete;
    print "Session will be deleted.\n";
}

print "\n</pre>\n";


# simple HTML form

printf <<'_HTML_', $q->escapeHTML($s->param('test'));
<hr/>
<form>
Session value "test": <input type="text" value="%s" name="test"/>
<button type="submit" name="save">Save Value</button>
<button type="submit" name="delete">Delete session</button>
</form>
_HTML_

# eof (linebreak needed after _HTML_)
于 2012-06-12T06:39:41.400 回答