ServersApache Session Management Within Dynamic Sites Page 4

Apache Session Management Within Dynamic Sites Page 4

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.




Using Apache::Session

Although cookies can be used to store all sorts of information, it is generally not a good idea to use them to store all the data. In particular, shopping basket information, user identification data (e.g., address, e-mail, and especially password and credit card information) should never be stored within a cookie.

This is because cookie data exchanged in HTTP headers can be snooped. Most browsers also include cookie viewing systems, which may further expose data to prying eyes. Exposing this information when there is no need to do so is obviously a bad idea.

Instead, you should store the session ID in a cookie and then associate the session ID with a store of information about the user that you want to keep. This information can be stored in a file or a database. You should always be able to find the user information because it has been identified with the session ID.

Storing the information can be complex, but another module can simplify the procedure: Apache::Session. With Apache::Session a hash is ‘tied’ to a set of data associated with a specific sessionid — the actual storage behind the scenes can be through a file or a database, with Apache::Session handling the reading and writing of the information for you.

At its simplest, Apache::Session works like this code fragment:

tie(%session_data, 'Apache::Session::File', 
    $sessionid, {Directory => '/tmp/'});
$session_data{basketitem} = 'Computer';
$session_data{CC_data} = '1234 5678 9012 3456';

The Apache::Session module creates a new session ID if the variable holding the session ID is undefined. If the session ID is defined, the module assumes it is a previously created session ID.

Data stored this way is persistent across connections, provided the same session ID is supplied by the browser each time. The data associated with an ID is recorded in a file on the server. The example in the next section combines the modules to provide session IDs and storage.

Combining Apache::Session and CGI

Below is a small CGI application that determines whether a cookie has already been defined. The CGI script should work in three stages:

  1. If the cookie is not defined, a new session ID is created, a new cookie for the session is sent to the browser, and we announce what we are doing.
  2. If the session ID exists, but there is no message written in the session data, we save a message.
  3. If the session ID exists and a message exists in our session data, then we print out the message.
#!/usr/bin/perl
use CGI;
use Apache::Session::File;
my %session_data;
my $query = new CGI;
my $session = $query->cookie('SESSIONID') || '';
if ($session =~ m/[a-zA-Z0-9]/)
{
    print($query->header(),
          $query->start_html('A Cookie Example'),
          $query->h1('A Cookie Example'));
    print $query->p("You have a cookie set ($session)");
    eval {
        tie(%session_data,
            'Apache::Session::File',
            $session,
            { Directory => '/tmp/sessions'});
    };
    if ($@)
    {
        die "Couldn't tie: $@";
    }
    if (exists($session_data{message}))
    {
        print($query->p('Have a message for you:'),
              $query->p($session_data{message}));
    }
    else
    {
        print "Recording a message for you";
        $session_data{message} = 'Aint nobody here but us chickens';
    }
    untie %session;
}
else
{
    my $session = undef;
    eval {
        tie(%session_data,
            'Apache::Session::File',
            $session,
            { Directory => '/tmp/sessions'});
    };
    if ($@)
    {
        die "Couldn't tie: $@";
    }
    $cookie = $query->cookie(-name=>'SESSIONID',
                             -value=> $session_data{_session_id},
                             -expires=>'+24h',
                             -path=>'/',
                             );
    print($query->header(-cookie=>$cookie),
          $query->start_html('A Cookie Example'),
          $query->h1('A Cookie Example'),
          "Setting a new cookie");
}

You can see here that the structure is comparatively straightforward — we supply the cookie and read the cookie data if it exists. Adding data to our session is just a case of assigning the information we want to store to a key within the hash. You should easily be able to adapt the above script for your own applications.

Summary

This article covered the fundamentals of the session process — the definition of a session, the semantics and theory of how to use cookies to create and manage a session, followed by a detailed look at a Perl script that handles both the session and session data. It is the combination of using cookies to create a session and using session data to hold information, such as purchases or preferences, that provide the personalization in many Web sites, including stores like Amazon or customized environments like My Yahoo.

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories