Apache::Session – A persistence framework for session data
| Use Case | Command | Description |
|---|---|---|
| Create a new session | tie %session, 'Apache::Session::MySQL', undef, { DataSource => 'dbi:mysql:sessions' }; | 🌱 Create a fresh session for a first-time visitor |
| Restore an existing session | tie %session, 'Apache::Session::MySQL', $session_id, { DataSource => 'dbi:mysql:sessions' }; | 🔄 Restore a session using a known session ID |
| Store data in a session | $session{first_name} = "Chuck"; | 💾 Store arbitrary data (scalars, references, objects) |
| Read the session ID | my $id = $session{_session_id}; | 🔑 Retrieve the magic session ID |
| Delete a session permanently | tied(%session)->delete; | 🗑️ Remove the session from the object store immediately |
| Use locking with transactions | tie %s, 'Apache::Session::File', $id, { Directory => '/tmp/sessions', Transaction => 1 }; | 🔒 Enable transactional consistency (supported by File, Berkeley DB; not MySQL/Postgres) |
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;
Apache::Session is a persistence framework particularly useful for tracking session data between httpd requests. It works with Apache and mod_perl, but also under CGI, other web servers, and outside a web server altogether.
Five components: interface (Session.pm), object store (filesystem, Berkeley DB, MySQL, Oracle, Postgres, Sybase, Informix), lock manager (lock files, semaphores, database locking), ID generator (MD5), serializer (Storable, optional MIME/pack). A derived class ties these together; e.g. Apache::Session::MySQL uses MySQL storage and locking.
Simple: tie a hash to the desired class. Constructor takes two optional arguments: session ID (or undef for new), and a hash of options for store/locker classes.
Get a new session using DBI:
tie %session, 'Apache::Session::MySQL', undef,
{ DataSource => 'dbi:mysql:sessions' };
Restore an old session:
tie %session, 'Apache::Session::MySQL', $session_id,
{ DataSource => 'dbi:mysql:sessions' };
$session{first_name} = "Chuck";
$session{an_array_ref} = [ $one, $two, $three ];
$session{an_object} = Some::Class->new;
The session ID is the only magic entry; anything beginning with "_" is reserved.
my $id = $session{_session_id};
tied(%session)->delete;
When creating a new session, it immediately saves to the data store (or dies on failure) and obtains an exclusive lock. When retrieving an existing session, it restores the object and obtains a non-exclusive lock. Data is stored as you assign to the hash. On untie() or scope exit, checks for changes; if changed, obtains exclusive lock and writes. Releases locks afterward. Only shallow change detection; top-level hash changes only. Timestamp the session hash to force updates. delete() removes immediately. Errors call die(); wrap in eval.
Default locking prevents data corruption but does not provide transactional consistency. To enable transactions, pass Transaction => 1 when tieing:
tie %s, 'Apache::Session::File', $id {
Directory => '/tmp/sessions',
LockDirectory => '/var/lock/sessions',
Transaction => 1
};
Note: Transaction has no practical effect on MySQL and Postgres implementations (MySQL only supports exclusive locking; Postgres uses its own transaction features).
How you implement depends on your needs. Hints:
Apache::Session::File – simple, no database neededApache::Session::MySQL, Apache::Session::Postgres, Apache::Session::Oracle, Apache::Session::Sybase, Apache::Session::Informix – for shared accessApache::Session::DB_File – fast, localApache::Session::Generate::ModUniqueID / ModUsertrackPrimarily designed for tracking user sessions between http requests, but also usable for sharing global data between httpd processes.
Decide on a session ID (e.g., "1") and ensure an object with that ID exists in the store before starting Apache. Example:
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...
Undef or untie the session hash as soon as done to free locks.
This example uses cookies. Apache::Session::Generate::ModUsertrack uses Apache's mod_usertrack for 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, or a new session
my %session;
tie %session, 'Apache::Session::MySQL', $cookie, {
DataSource => 'dbi:mysql:sessions',
UserName => 'mySQL_user',
Password => 'password',
LockDataSource => 'dbi:mysql:sessions',
LockUserName => 'mySQL_user',
LockPassword => 'password'
};
#Might be a new session, so give them their cookie back
my $session_cookie = "SESSION_ID=$session{_session_id};";
$r->header_out("Set-Cookie" => $session_cookie);
#program continues...
Session – OO interface to Apache::SessionUnder the same terms as Perl itself.
Generated by phpman v4.9.29 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-22 00:55 @2600:1f28:365:80b0:d8a5:c3c6:bf94:28c0
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format