Sunday, January 9, 2011

Working with session variables

The following "set_session.pl" program shows how to set values in session variables:
#!/usr/bin/perl

use CGI;

use CGI::Session; # module required for using session variables 

my $cgi = new CGI;

# object initialized for accesing session variables
my $session = CGI::Session->new();

# setting values in user defined session variables
$session->param('my_name', 'James');
$session->param('my_age', '36');

# defining a cookie with the name "session_id" and storing the current session id as it's value, to be used later for accessing the values stored in the current session variables
my $cookie = CGI::Cookie->new( -name => "session_id", -value => $session->id );

# setting the cookie
print $cgi->header( -cookie =>  $cookie  );

print "Values stored in the session.";

The following "get_session.pl" program will read the values stored in the session variable set in the earlier program:
#!/usr/bin/perl

use CGI;

use CGI::Session;

my $cgi = new CGI;

print $cgi->header();

# retrieving the session id stored in the "session_id" cookie for accessing the earlier set session variables
my $session_id = $cgi->cookie("session_id");

# object initialized for accesing session variables from the passed session id
my $session = CGI::Session->new($session_id);

# fetching the values stored in session variables
my $name = $session->param('my_name');
my $age = $session->param('my_age');

print "My name is $name and I am $age years old.";


Output:
-------
On calling the "set_session.pl" program from browser, it will set an user defined name and age in session variables named 'my_name' and 'my_age' respectively to be accessed by other programs in the current session, the session id of the current session is stored in a cookie named "session_id" and then on calling the "get_session.pl" program from browser, it will fetch the session id stored in the cookie named "session_id" for accessing the session variables associated with id.