Apache::Session(3pm)
π NAME π
Apache::Session β a whole persistence framework for session data. That's the name, bestie, that's the assignment. π«Ά
β¨ SYNOPSIS β¨
use Apache::Session::MySQL;
my %session;
#make a fresh session for a first-time visitor
tie %session, 'Apache::Session::MySQL';
#stick some stuff in it
$session{visa_number} = "1234 5678 9876 5432";
#get the session id for later use
my $id = $session{_session_id};
#...time passes...
#get the session data back out again during some other request
my %session;
tie %session, 'Apache::Session::MySQL', $id;
validate($session{visa_number});
#delete a session from the object store permanently
tied(%session)->delete;
π DESCRIPTION π
Okay so Apache::Session is a persistence framework β and it's especially useful for tracking session data between httpd requests. It's built to work with Apache and mod_perl, but ngl it should also work under CGI and other web servers, and honestly it works outside of a web server entirely too. Versatile queen. π
Apache::Session is made of five components, and yes we're naming all of them:
- the interface
- the object store
- the lock manager
- the ID generator
- the serializer
The interface lives in Session.pm, and it's meant to be easily subclassed. The object store can be the filesystem, a Berkeley DB, a MySQL DB, an Oracle DB, a Postgres DB, Sybase, or Informix. Locking gets done by lock files, semaphores, or the locking capabilities of the various databases. Serialization happens via Storable, and it can optionally be ASCII-fied via MIME or pack(). ID numbers get generated via MD5. And the reader β that's you, bestie β is encouraged to extend all these capabilities to meet your own requirements. Go off. β¨
A derived class of Apache::Session is what ties together the three following components. That derived class inherits the interface from Apache::Session, and specifies which store and locker classes to use. Apache::Session::MySQL, for instance, uses the MySQL storage class and also the MySQL locking class. And you can easily plug in your own object store or locker class. Mix and match, it's giving custom. π
π INTERFACE π
The interface to Apache::Session is so simple: tie a hash to the desired class and use the hash as normal. That's it. The constructor takes two optional arguments:
- the first argument is the desired session ID number, or
undeffor a new session - the second argument is a hash of options that will be passed to the object store and locker classes
π tieing the session π
Get a new session using DBI:
tie %session, 'Apache::Session::MySQL', undef,
{ DataSource => 'dbi:mysql:sessions' };
Restore an old session from the database:
tie %session, 'Apache::Session::MySQL', $session_id,
{ DataSource => 'dbi:mysql:sessions' };
π Storing and retrieving data to and from the session π
Hey, how much easier could it get? Literally this easy:
$session{first_name} = "Chuck";
$session{an_array_ref} = [ $one, $two, $three ];
$session{an_object} = Some::Class->new;
π¦ Reading the session ID π¦
The session ID is the only magic entry in the session object β but heads up, anything beginning with an "_" is considered reserved for future use. Don't go naming your own keys like that, okay? π
my $id = $session{_session_id};
π Permanently removing the session from storage π
tied(%session)->delete;
πΈ BEHAVIOR πΈ
Apache::Session tries to behave the way the author believes you would expect. Which is a vibe, honestly. Here's the rundown:
- When you create a new session, Session immediately saves the session to the data store, or calls
die()if it cannot. It also obtains an exclusive lock on the session object. - If you retrieve an existing session, Session immediately restores the object from storage, or calls
die()in case of an error. Session also obtains a non-exclusive lock on the session.
As you put data into the session hash, Session squirrels it away for later use. πΏοΈ When you untie() the session hash, or it passes out of scope, Session checks to see if anything has changed. If so, Session gains an exclusive lock and writes the session to the data store. Then it releases any locks it has acquired. Clean. Tidy. Iconic.
β οΈ Note that Apache::Session does only a shallow check to see if anything has changed. If nothing changes in the top level tied hash, the data will not be updated in the backing store. You are encouraged to timestamp the session hash so that it is sure to be updated. Don't get caught out by this one, fr fr.
When you call the delete() method on the session object, the object is immediately removed from the object store, if possible.
When Session encounters an error, it calls die(). You will probably want to wrap your session logic in an eval block to trap these errors. Protect your peace. π«Ά
π₯ LOCKING AND TRANSACTIONS π₯
By default, most Apache::Session implementations only do locking to prevent data corruption. That locking scheme does not provide transactional consistency, like the kind you might get from a relational database. So if you desire transactional consistency, you must provide the Transaction argument with a true value when you tie the session hash. For example:
tie %s, 'Apache::Session::File', $id {
Directory => '/tmp/sessions',
LockDirectory => '/var/lock/sessions',
Transaction => 1
};
Note that the Transaction argument has no practical effect on the MySQL and Postgres implementations. The MySQL implementation only supports exclusive locking, and the Postgres implementation uses the transaction features of that database. So, y'know. Know your store. π
π IMPLEMENTATION π
The way you implement Apache::Session depends on what you are trying to accomplish. Here are some hints on which classes to use in what situations. π
β STRATEGIES β
Apache::Session is mainly designed to track user session between http requests. However, it can also be used for any situation where data persistence is desirable. For example, it could be used to share global data between your httpd processes. The following examples are short mod_perl programs which demonstrate some session handling basics.
π Sharing data between Apache processes π
When you share data between Apache processes, you need to decide on a session ID number ahead of time and make sure that an object with that ID number is in your object store before starting your Apache. How you accomplish that is your own business. I use the session ID "1". Here is a short program in which we use Apache::Session to store out database access information.
use Apache;
use Apache::Session::File;
use DBI;
use strict;
my %global_data;
eval {
tie %global_data, 'Apache::Session::File', 1,
{Directory => '/tmp/sessiondata'};
};
if ($@) {
die "Global data is not accessible: $@";
}
my $dbh = DBI->connect($global_data{datasource},
$global_data{username}, $global_data{password}) || die $DBI::errstr;
undef %global_data;
#program continues...
As shown in this example, you should undef or untie your session hash as soon as you are done with it. This will free up any locks associated with your process. Locks are not it, bestie, let them go. ποΈ
π Tracking users with cookies π
The choice of whether to use cookies or path info to track user IDs is a rather religious topic among Apache users. This example uses cookies. The implementation of a path info system is left as an exercise for the reader. π
Note thatApache::Session::Generate::ModUsertrackuses Apache'smod_usertrackcookies to generate and maintain session IDs.
use Apache::Session::MySQL;
use Apache;
use strict;
#read in the cookie if this is an old session
my $r = Apache->request;
my $cookie = $r->header_in('Cookie');
$cookie =~ s/SESSION_ID=(\w*)/$1/;
#create a session object based on the cookie we got from the browser,
#or a new session if we got no cookie
my %session;
tie %session, 'Apache::Session::MySQL', $cookie, {
DataSource => 'dbi:mysql:sessions', #these arguments are
UserName => 'mySQL_user', #required when using
Password => 'password', #MySQL.pm
LockDataSource => 'dbi:mysql:sessions',
LockUserName => 'mySQL_user',
LockPassword => 'password'
};
#Might be a new session, so lets give them their cookie back
my $session_cookie = "SESSION_ID=$session{_session_id};";
$r->header_out("Set-Cookie" => $session_cookie);
#program continues...
π SEE ALSO π
Apache::Session::MySQLApache::Session::PostgresApache::Session::FileApache::Session::DB_FileApache::Session::OracleApache::Session::Sybase
The O Reilly book "Apache Modules in Perl and C", by Doug MacEachern and Lincoln Stein, has a chapter on keeping state. π
CGI::Session uses OO interface to do same thing. It is better maintained, but less possibilies.
Catalyst::Plugin::Session β support of sessions in Catalyst
Session β OO interface to Apache::Session
π§ LICENSE π§
Under the same terms as Perl itself.
π«Ά AUTHORS π«Ά
- Alexandr Ciornii,
<http://chorny.net>β current maintainer - Jeffrey Baker
<jwbaker@acm.org>is the author of Apache::Session. - Tatsuhiko Miyagawa
<miyagawa@bulknews.net>is the author ofGenerate::ModUniqueIDandGenerate::ModUsertrack - Erik Rantapaa
<rantapaa@fanbuzz.com>found errors in bothLock::FileandStore::File - Bart Schaefer
<schaefer@zanshin.com>notified me of a bug inLock::File. - Chris Winters
<cwinters@intes.net>contributed the Sybase code. - Michael Schout
<mschout@gkg.net>fixed a commit policy bug in 1.51. - Andreas J. Koenig
<andreas.koenig@anima.de>contributed valuable CPAN advice and alsoApache::Session::TreeandApache::Session::Counted. - Gerald Richter
<richter@ecos.de>had the idea for a tied hash interface and provided the initial code for it. He also uses Apache::Session in his Embperl module and is the author ofApache::Session::Embperl - Jochen Wiedmann
<joe@ipsoft.de>contributed patches for bugs and improved performance. - Steve Shreeve
<shreeve@uci.edu>squashed a bug in 0.99.0 whereby a cleared hash or deleted key failed to set the modified bit. - Peter Kaas
<Peter.Kaas@lunatech.com>sent quite a bit of feedback with ideas for interface improvements. - Randy Harmon
<rjharmon@uptimecomputers.com>contributed the original storage-independent object interface with input from:- Bavo De Ridder
<bavo@ace.ulyssis.student.kuleuven.ac.be> - Jules Bean
<jmlb2@hermes.cam.ac.uk> - Lincoln Stein
<lstein@cshl.org>
- Bavo De Ridder
- Jamie LeTaul
<jletual@kmtechnologies.com>fixed file locking on Windows. - Scott McWhirter
<scott@surreytech.co.uk>contributed verbose error messages for file locking. - Corris Randall
<corris@line6.net>gave us the option to use any table name in the MySQL store. - Oliver Maul
<oliver.maul@ixos.de>updated the Sybase modules - Innumerable users sent a patch for the reversed file age test in the file locking module.
- Langen Mike
<mike.langen@tamedia.ch>contributed Informix modules.
and that's the whole page, bestie!! πβ¨ππ¦πΈπ π«Άππβ this was documented with perl v5.36.0, dated 2022-11-19, and it's the Apache::Session(3pm) manual page β go tie a hash, timestamp it, and free those locks. periodt. π
π¦ where this page comes from
- debian bookworm: libapache-session-perl 1.94-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libapache-session-perl 1.94-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libapache-session-perl 1.94-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libapache-session-perl 1.94-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libapache-session-perl 1.94-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms