Wednesday, September 26, 2012

Perl Sessions...filling in the gaps

I recently had to utilize the perl CGI::Session module and found the documentation a little odd and somewhat vague in certain areas. So for my sanity and hopefully anyone else that runs across this, I'm going to take a moment to explain how to use this module so that you too can get up and running quick.

Sessions...How do they work?

Sessions are fairly basic, the goal is to store some information on the client that will allow us to work around the Internet being stateless. Now there are only a couple ways to do this. The first way is the most common method of storing the user's session id in a cookie. But what if the user doesn't accept cookies? Well that would make the first method a bit hard now wouldn't it? Luckily we can always fall back on storing the user's session id in a hidden variable within the page. The Session module handles sessions in this way as well by defaulting to using cookies. Now I'm sure you are thinking, well great so you have an id for the user's session. But how do we use it? At this point you need to track the user on the server. To do this you can either:
  • save the session data to a file
    or
  • store the session data in a database table with the session id as the primary key.
Getting started:

Before we can use the Sessions module we need to make sure we have included both the CGI and the CGI::Session module. We also need an instance of the CGI object. The code to this is as follows:

use CGI qw/:standard/; # for parsing form data
use CGI::Session qw/-ip-match/;
my $cgi = new CGI();

Now that we have added the modules we can start a session. First, we usually want to make sure that the user doesn't already have a session open. To do this we use the following.

my $session_id = $cgi->cookie('session_name') || $cgi->param('session_name') || undef;

You see in the first thing we check is if there is a cookie in place with the name assigned to identify it with $cgi->cookie('session_name'). If there isn't one then we may want to check to make sure that there wasn't a hidden variable passed to the server with the session_id. Now that we know that we have the session_id set we can create a new session.

my $session = new CGI::Session("driver:File", $session_id, {Directory=>'/tmp'});

Here we are passing a few parameters to the Session() function.
  1. Driver : This parameter is used to define how the data will be stored. In this instance the data will be stored in a file.
  2. Session ID : The users session id. If the user already has a session open then this will use that users session. If it doesn't however, then the module will start a new session.
  3. Directory : This is used to specify what directory the module should save sessions to.
There is a lot more to the module than what I have explained here. You can get the full CPAN documentation here .

No comments:

Post a Comment