CGI::Session - persistent session data in CGI applications


    # Object initialization:
    use CGI::Session;

    my $session = new CGI::Session("driver:File", undef, {Directory=>'/tmp'});

    # getting the effective session id:
    my $CGISESSID = $session->id();

    # storing data in the session
    $session->param('f_name', 'Sherzod');
    # or
    $session->param(-name=>'l_name', -value=>'Ruzmetov');

    # retrieving data
    my $f_name = $session->param('f_name');
    # or
    my $l_name = $session->param(-name=>'l_name');

    # clearing a certain session parameter

    # expire '_IS_LOGGED_IN' flag after 10 idle minutes:
    $session->expire(_IS_LOGGED_IN => '+10m')

    # expire the session itself after 1 idle hour

    # delete the session for good


CGI-Session is a Perl5 library that provides an easy, reliable and modular session management system across HTTP requests. Persistency is a key feature for such applications as shopping carts, login/authentication routines, and application that need to carry data accross HTTP requests. CGI::Session does that and many more


Current manual is optimized to be used as a quick reference. To learn more both about the logic behind session management and CGI::Session programming style, consider the following:

  • CGI::Session::Tutorial - extended CGI::Session manual. Also includes library architecture and driver specifications.

  • CGI::Session::CookBook - practical solutions for real life problems

  • We also provide mailing lists for CGI::Session users. To subscribe to the list or browse the archives visit

  • RFC 2965 - "HTTP State Management Mechanism" found at

  • CGI - standard CGI library

  • Apache::Session - another fine alternative to CGI::Session


Following is the overview of all the available methods accessible via CGI::Session object.


Requires three arguments. First is the Data Source Name, second should be the session id to be initialized or an object which provides either of 'param()' or 'cookie()' mehods. If Data Source Name is undef, it will fall back to default values, which are "driver:File;serializer:Default;id:MD5".

If session id is missing, it will force the library to generate a new session id, which will be accessible through id() method.


    $session = new CGI::Session(undef, undef, {Directory=>'/tmp'});
    $session = new CGI::Session("driver:File;serializer:Storable", undef,  {Directory=>'/tmp'})
    $session = new CGI::Session("driver:MySQL;id:Incr", undef, {Handle=>$dbh});

Following data source variables are supported:

  • driver - CGI::Session driver. Available drivers are "File", "DB_File" and "MySQL". Default is "File".

  • serializer - serializer to be used to encode the data structure before saving in the disk. Available serializers are "Storable", "FreezeThaw" and "Default". Default is "Default", which uses standard Data::Dumper

  • id - ID generator to use when new session is to be created. Available ID generators are "MD5" and "Incr". Default is "MD5".

Note: you can also use unambiguous abbreviations of the DSN parameters. Examples:

    new CGI::Session("dr:File;ser:Storable", undef, {Diretory=>'/tmp'});

Returns effective ID for a session. Since effective ID and claimed ID can differ, valid session id should always be retrieved using this method.


this method used in either of the above syntax returns a session parameter set to $name or undef on failure.

param( $name, $value)
param(-name=>$name, -value=>$value)

method used in either of the above syntax assigns a new value to $name parameter, which can later be retrieved with previously introduced param() syntax.


returns all the session parameters as a reference to a hash

save_param($cgi, $arrayref)

Saves CGI parameters to session object. In otherwords, it's calling param($name, $value) for every single CGI parameter. The first argument should be either CGI object or any object which can provide param() method. If second argument is present and is a reference to an array, only those CGI parameters found in the array will be stored in the session

load_param($cgi, $arrayref)

loads session parameters to CGI object. The first argument is required to be either object, or any other object which can provide param() method. If second argument is present and is a reference to an array, only the parameters found in that array will be loaded to CGI object.

sync_param($cgi, $arrayref)

experimental feature. Synchronizes CGI and session objects. In other words, it's the same as calling respective syntaxes of save_param() and load_param().


clears parameters from the session object. If passed an argument as an arrayref, clears only those parameters found in the list.


synchronizes data in the buffer with its copy in disk. Normally it will be called for you just before the program terminates, session object goes out of scope or close() is called.


closes the session temporarily until new() is called on the same session next time. In other words, it's a call to flush() and DESTROY(), but a lot slower. Normally you never have to call close().


returns the last access time of the session in the form of seconds from epoch. This time is used internally while auto-expiring sessions and/or session parameters.


returns the time when the session was first created.

expire($param, $time)

Sets expiration date relative to atime(). If used with no arguments, returns the expiration date if it was ever set. If no expiration was ever set, returns undef.

Second form sets an expiration time. This value is checked when previously stored session is asked to be retrieved, and if its expiration date has passed will be expunged from the disk immediately and new session is created accordingly. Passing 0 would cancel expiration date.

By using the third syntax you can also set an expiration date for a particular session parameter, say "~logged-in". This would cause the library call clear() on the parameter when its time is up.

All the time values should be given in the form of seconds. Following time aliases are also supported for your convenience:

    |   alias   |   meaning     |
    |     s     |   Second      |
    |     m     |   Minute      |
    |     h     |   Hour        |
    |     w     |   Week        |
    |     M     |   Month       |
    |     y     |   Year        |


    $session->expires("+1y");   # expires in one year
    $session->expires(0);       # cancel expiration
    $session->expires("~logged-in", "+10m");# expires ~logged-in flag in 10 mins

Note: all the expiration times are relative to session's last access time, not to its creation time. To expire a session immediately, call delete(). To expire a specific session parameter immediately, call clear() on that parameter.


returns the remote address of the user who created the session for the first time. Returns undef if variable REMOTE_ADDR wasn't present in the environment when the session was created


deletes the session from the disk. In other words, it calls for immediate expiration after which the session will not be accessible


returns the last error message from the library. It's the same as the value of $CGI::Session::errstr. Example:

    $session->flush() or die $session->error();

creates a dump of the session object. Argument, if passed, will be interpreted as the name of the file object should be dumped in. Used mostly for debugging.


header() is simply a replacement for's header() method. Without this method, you usually need to create a CGI::Cookie object and send it as part of the HTTP header:

    $cookie = new CGI::Cookie(-name=>'CGISESSID', -value=>$session->id);
    print $cgi->header(-cookie=>$cookie);

You can minimize the above into:


It will retrieve the name of the session cookie from $CGI::Session::NAME variable, which can also be accessed via CGI::Session->name() method. If you want to use a different name for your session cookie, do something like following before creating session object:

    $session = new CGI::Session(undef, $cgi, \%attrs);

Now, $session->header() uses "MY_SID" as a name for the session cookie.


Session data is stored in the form of hash table, in key value pairs. All the parameter names you assign through param() method become keys in the table, and whatever value you assign become a value associated with that key. Every key/value pair is also called a record.

All the data you save through param() method are called public records. There are several read-only private records as well. Normally, you don't have to know anything about them to make the best use of the library. But knowing wouldn't hurt either. Here are the list of the private records and some description of what they hold:


Session id of that data. Accessible through id() method.


Session creation time. Accessible through ctime() method.


Session last access time. Accessible through atime() method.


Session's expiration time, if any. Accessible through expire() method.


IP address of the user who create that session. Accessible through remote_addr() method


Another internal hash table that holds the expiration information for each expirable public record, if any. This table is updated with the two-argument-syntax of expires() method.

These private methods are essential for the proper operation of the library while working with session data. For this purpose, CGI::Session doesn't allow overriding any of these methods through the use of param() method. In addition, it doesn't allow any parameter names that start with string _SESSION_ either to prevent future collisions.

So the following attempt will have no effect on the session data whatsoever

    $session->param(_SESSION_XYZ => 'xyz');

Although private methods are not writable, the library allows reading them using param() method:

    my $sid = $session->param(_SESSION_ID);

The above is the same as:

    my $sid = $session->id();

But we discourage people from accessing private records using param() method. In the future we are planning to store private records in their own namespace to avoid name collisions and remove restrictions on session parameter names.


CGI::Session consists of several modular components such as drivers, serializers and id generators. This section lists what is available.


Following drivers are included in the standard distribution:

  • File - default driver for storing session data in plain files. Full name: CGI::Session::File

  • DB_File - for storing session data in BerkelyDB. Requires: DB_File. Full name: CGI::Session::DB_File

  • MySQL - for storing session data in MySQL tables. Requires DBI and DBD::mysql. Full name: CGI::Session::MySQL



Following ID generators are available:

  • MD5 - generates 32 character long hexidecimal string. Requires Digest::MD5. Full name: CGI::Session::ID::MD5.

  • Incr - generates auto-incrementing ids. Full name: CGI::Session::ID::Incr


Copyright (C) 2001-2002 Sherzod Ruzmetov <>. All rights reserved.

This library is free software. You can modify and or distribute it under the same terms as Perl itself.


Sherzod Ruzmetov <>. Feedbacks, suggestions are welcome.