{
    "mode": "perldoc",
    "parameter": "Apache::Session",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Apache%3A%3ASession/json",
    "generated": "2026-06-09T17:15:13Z",
    "synopsis": "use Apache::Session::MySQL;\nmy %session;\n#make a fresh session for a first-time visitor\ntie %session, 'Apache::Session::MySQL';\n#stick some stuff in it\n$session{visanumber} = \"1234 5678 9876 5432\";\n#get the session id for later use\nmy $id = $session{sessionid};\n#...time passes...\n#get the session data back out again during some other request\nmy %session;\ntie %session, 'Apache::Session::MySQL', $id;\nvalidate($session{visanumber});\n#delete a session from the object store permanently\ntied(%session)->delete;",
    "sections": {
        "NAME": {
            "content": "Apache::Session - A persistence framework for session data\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use Apache::Session::MySQL;\n\nmy %session;\n\n#make a fresh session for a first-time visitor\ntie %session, 'Apache::Session::MySQL';\n\n#stick some stuff in it\n$session{visanumber} = \"1234 5678 9876 5432\";\n\n#get the session id for later use\nmy $id = $session{sessionid};\n\n#...time passes...\n\n#get the session data back out again during some other request\nmy %session;\ntie %session, 'Apache::Session::MySQL', $id;\n\nvalidate($session{visanumber});\n\n#delete a session from the object store permanently\ntied(%session)->delete;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Apache::Session is a persistence framework which is particularly useful for tracking session\ndata between httpd requests. Apache::Session is designed to work with Apache and modperl, but\nit should work under CGI and other web servers, and it also works outside of a web server\naltogether.\n\nApache::Session consists of five components: the interface, the object store, the lock manager,\nthe ID generator, and the serializer. The interface is defined in Session.pm, which is meant to\nbe easily subclassed. The object store can be the filesystem, a Berkeley DB, a MySQL DB, an\nOracle DB, a Postgres DB, Sybase, or Informix. Locking is done by lock files, semaphores, or the\nlocking capabilities of the various databases. Serialization is done via Storable, and\noptionally ASCII-fied via MIME or pack(). ID numbers are generated via MD5. The reader is\nencouraged to extend these capabilities to meet his own requirements.\n\nA derived class of Apache::Session is used to tie together the three following components. The\nderived class inherits the interface from Apache::Session, and specifies which store and locker\nclasses to use. Apache::Session::MySQL, for instance, uses the MySQL storage class and also the\nMySQL locking class. You can easily plug in your own object store or locker class.\n",
            "subsections": []
        },
        "INTERFACE": {
            "content": "The interface to Apache::Session is very simple: tie a hash to the desired class and use the\nhash as normal. The constructor takes two optional arguments. The first argument is the desired\nsession ID number, or undef for a new session. The second argument is a hash of options that\nwill be passed to the object store and locker classes.\n\ntieing the session\nGet a new session using DBI:\n\ntie %session, 'Apache::Session::MySQL', undef,\n{ DataSource => 'dbi:mysql:sessions' };\n\nRestore an old session from the database:\n\ntie %session, 'Apache::Session::MySQL', $sessionid,\n{ DataSource => 'dbi:mysql:sessions' };\n",
            "subsections": [
                {
                    "name": "Storing and retrieving data to and from the session",
                    "content": "Hey, how much easier could it get?\n\n$session{firstname} = \"Chuck\";\n$session{anarrayref} = [ $one, $two, $three ];\n$session{anobject} = Some::Class->new;\n"
                },
                {
                    "name": "Reading the session ID",
                    "content": "The session ID is the only magic entry in the session object, but anything beginning with an \"\"\nis considered reserved for future use.\n\nmy $id = $session{sessionid};\n"
                },
                {
                    "name": "Permanently removing the session from storage",
                    "content": "tied(%session)->delete;\n"
                }
            ]
        },
        "BEHAVIOR": {
            "content": "Apache::Session tries to behave the way the author believes that you would expect. When you\ncreate a new session, Session immediately saves the session to the data store, or calls die() if\nit cannot. It also obtains an exclusive lock on the session object. If you retrieve an existing\nsession, Session immediately restores the object from storage, or calls die() in case of an\nerror. Session also obtains a non-exclusive lock on the session.\n\nAs you put data into the session hash, Session squirrels it away for later use. When you untie()\nthe session hash, or it passes out of scope, Session checks to see if anything has changed. If\nso, Session gains an exclusive lock and writes the session to the data store. It then releases\nany locks it has acquired.\n\nNote that Apache::Session does only a shallow check to see if anything has changed. If nothing\nchanges in the top level tied hash, the data will not be updated in the backing store. You are\nencouraged to timestamp the session hash so that it is sure to be updated.\n\nWhen you call the delete() method on the session object, the object is immediately removed from\nthe object store, if possible.\n\nWhen Session encounters an error, it calls die(). You will probably want to wrap your session\nlogic in an eval block to trap these errors.\n",
            "subsections": []
        },
        "LOCKING AND TRANSACTIONS": {
            "content": "By default, most Apache::Session implementations only do locking to prevent data corruption. The\nlocking scheme does not provide transactional consistency, such as you might get from a\nrelational database. If you desire transactional consistency, you must provide the Transaction\nargument with a true value when you tie the session hash. For example:\n\ntie %s, 'Apache::Session::File', $id {\nDirectory     => '/tmp/sessions',\nLockDirectory => '/var/lock/sessions',\nTransaction   => 1\n};\n\nNote that the Transaction argument has no practical effect on the MySQL and Postgres\nimplementations. The MySQL implementation only supports exclusive locking, and the Postgres\nimplementation uses the transaction features of that database.\n",
            "subsections": []
        },
        "IMPLEMENTATION": {
            "content": "The way you implement Apache::Session depends on what you are trying to accomplish. Here are\nsome hints on which classes to use in what situations\n",
            "subsections": []
        },
        "STRATEGIES": {
            "content": "Apache::Session is mainly designed to track user session between http requests. However, it can\nalso be used for any situation where data persistence is desirable. For example, it could be\nused to share global data between your httpd processes. The following examples are short\nmodperl programs which demonstrate some session handling basics.\n",
            "subsections": [
                {
                    "name": "Sharing data between Apache processes",
                    "content": "When you share data between Apache processes, you need to decide on a session ID number ahead of\ntime and make sure that an object with that ID number is in your object store before starting\nyour Apache. How you accomplish that is your own business. I use the session ID \"1\". Here is a\nshort program in which we use Apache::Session to store out database access information.\n\nuse Apache;\nuse Apache::Session::File;\nuse DBI;\n\nuse strict;\n\nmy %globaldata;\n\neval {\ntie %globaldata, 'Apache::Session::File', 1,\n{Directory => '/tmp/sessiondata'};\n};\nif ($@) {\ndie \"Global data is not accessible: $@\";\n}\n\nmy $dbh = DBI->connect($globaldata{datasource},\n$globaldata{username}, $globaldata{password}) || die $DBI::errstr;\n\nundef %globaldata;\n\n#program continues...\n\nAs shown in this example, you should undef or untie your session hash as soon as you are done\nwith it. This will free up any locks associated with your process.\n"
                },
                {
                    "name": "Tracking users with cookies",
                    "content": "The choice of whether to use cookies or path info to track user IDs is a rather religious topic\namong Apache users. This example uses cookies. The implementation of a path info system is left\nas an exercise for the reader.\n\nNote that Apache::Session::Generate::ModUsertrack uses Apache's modusertrack cookies to\ngenerate and maintain session IDs.\n\nuse Apache::Session::MySQL;\nuse Apache;\n\nuse strict;\n\n#read in the cookie if this is an old session\n\nmy $r = Apache->request;\nmy $cookie = $r->headerin('Cookie');\n$cookie =~ s/SESSIONID=(\\w*)/$1/;\n\n#create a session object based on the cookie we got from the browser,\n#or a new session if we got no cookie\n\nmy %session;\ntie %session, 'Apache::Session::MySQL', $cookie, {\nDataSource => 'dbi:mysql:sessions', #these arguments are\nUserName   => 'mySQLuser',         #required when using\nPassword   => 'password',           #MySQL.pm\nLockDataSource => 'dbi:mysql:sessions',\nLockUserName   => 'mySQLuser',\nLockPassword   => 'password'\n};\n\n#Might be a new session, so lets give them their cookie back\n\nmy $sessioncookie = \"SESSIONID=$session{sessionid};\";\n$r->headerout(\"Set-Cookie\" => $sessioncookie);\n\n#program continues...\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "Apache::Session::MySQL, Apache::Session::Postgres, Apache::Session::File,\nApache::Session::DBFile, Apache::Session::Oracle, Apache::Session::Sybase\n\nThe O Reilly book \"Apache Modules in Perl and C\", by Doug MacEachern and Lincoln Stein, has a\nchapter on keeping state.\n\nCGI::Session uses OO interface to do same thing. It is better maintained, but less possibilies.\n\nCatalyst::Plugin::Session - support of sessions in Catalyst\n\nSession - OO interface to Apache::Session\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "Under the same terms as Perl itself.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Alexandr Ciornii, <http://chorny.net> - current maintainer\n\nJeffrey Baker <jwbaker@acm.org> is the author of Apache::Session.\n\nTatsuhiko Miyagawa <miyagawa@bulknews.net> is the author of Generate::ModUniqueID and\nGenerate::ModUsertrack\n\nErik Rantapaa <rantapaa@fanbuzz.com> found errors in both Lock::File and Store::File\n\nBart Schaefer <schaefer@zanshin.com> notified me of a bug in Lock::File.\n\nChris Winters <cwinters@intes.net> contributed the Sybase code.\n\nMichael Schout <mschout@gkg.net> fixed a commit policy bug in 1.51.\n\nAndreas J. Koenig <andreas.koenig@anima.de> contributed valuable CPAN advice and also\nApache::Session::Tree and Apache::Session::Counted.\n\nGerald Richter <richter@ecos.de> had the idea for a tied hash interface and provided the initial\ncode for it. He also uses Apache::Session in his Embperl module and is the author of\nApache::Session::Embperl\n\nJochen Wiedmann <joe@ipsoft.de> contributed patches for bugs and improved performance.\n\nSteve Shreeve <shreeve@uci.edu> squashed a bug in 0.99.0 whereby a cleared hash or deleted key\nfailed to set the modified bit.\n\nPeter Kaas <Peter.Kaas@lunatech.com> sent quite a bit of feedback with ideas for interface\nimprovements.\n\nRandy Harmon <rjharmon@uptimecomputers.com> contributed the original storage-independent object\ninterface with input from:\n\nBavo De Ridder <bavo@ace.ulyssis.student.kuleuven.ac.be>\nJules Bean <jmlb2@hermes.cam.ac.uk>\nLincoln Stein <lstein@cshl.org>\n\nJamie LeTaul <jletual@kmtechnologies.com> fixed file locking on Windows.\n\nScott McWhirter <scott@surreytech.co.uk> contributed verbose error messages for file locking.\n\nCorris Randall <corris@line6.net> gave us the option to use any table name in the MySQL store.\n\nOliver Maul <oliver.maul@ixos.de> updated the Sybase modules\n\nInnumerable users sent a patch for the reversed file age test in the file locking module.\n\nLangen Mike <mike.langen@tamedia.ch> contributed Informix modules.\n",
            "subsections": []
        }
    },
    "summary": "Apache::Session - A persistence framework for session data",
    "flags": [],
    "examples": [],
    "see_also": []
}