16.4 Reconnecting to an existing session

The previous section shows us how to create a new session. In most scripts, however, we need to reconnect to an existing session, if one exists. As it turns out, this is fairly easy to do.

First, we must insert the following lines before the creation of the $session object:

use CGI;
my $cgi = new CGI;

This creates an CGI object. But it also lets the CGI object parse all the information contained in the header of the HTTP request. In other words, all the parameters and cookies are now parsed and ready to be access via methods of $cgi.

Next, we need to somehow pass the information contained in the HTTP request to the logic that creates the session object. We replace this line

my $session = new CGI::Session("driver:MySQL", undef, {Handle=>$dbh});

with the following:

my $session = new CGI::Session("driver:MySQL", $cgi, {Handle=>$dbh});

What is the difference? Instead of passing undef (which means undefined) as the second parameter, we pass $cgi. This is all it takes to reconnect to an existing session, if one exists. If the session has expired, or if there is no session ID cookie provided, a new session is created in the database table.

Copyright © 2008-05-09 by Tak Auyeung