Database Reference
In-Depth Information
Solution
The Apache::Session module provides a convenient way to use several different storage
types, including one based on MySQL.
Discussion
Apache::Session is an easy-to-use Perl module for maintaining state information across
multiple web requests. Despite the name, this module does not require Apache and can
be used in nonweb contexts—for example, to maintain persistent state across multiple
invocations of a command-line script.
Apache::Session does not handle issues associated with tracking the session ID (sending
it to the client in response to the initial request and extracting it from subsequent re‐
quests). The example application shown here uses cookies to pass the session ID, on the
assumption that the client has cookies enabled.
Apache::Session setup
several other modules that you may need to install first. (If you use a
cpan
install
Apache::Session
command, that should install the module and take care of dependen‐
cies.) After you have everything installed, create a table in which to store session records,
in any database you like (we'll use
cookbook
). The specification for the table comes from
the MySQL storage handler documentation, which you can read using this command:
%
perldoc Apache::Session::Store::MySQL
We'll use a table named
perl_session
with this structure:
CREATE
TABLE
perl_session
(
id
CHAR
(
32
)
NOT
NULL
,
#
session
identifier
a_session
LONGBLOB
,
#
session
data
PRIMARY
KEY
(
id
)
);
The
id
column holds session identifiers, which are unique 32-character MD5 values
generated by Apache::Session. The
a_session
column stores session data as serialized
strings. Apache::Session uses the Storable module to serialize and unserialize session
data. (The Apache::Session::Store::MySQL documentation indicates that
a_session
is
a
TEXT
column, but any
BLOB
or
TEXT
data type large enough to hold the anticipated
session records should work.)
The Apache::Session interface
To use the
perl_session
table in a script, include the MySQL-related session module:
use
Apache::Session::
MySQL
;