The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

CGI::Session - persistent session data in CGI applications

SYNOPSIS

# Object initialization:
use CGI::Session;
$session = new CGI::Session();

$CGISESSID = $session->id();

# Send proper HTTP header with cookies:
print $session->header();

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

# Flush the data from memory to the storage driver at least before your
# program finishes since auto-flushing can be unreliable.
# Warning: A bug in your logic whereby the DBI handle has gone
# out of scope before flush() is called means flush() won't work
# (when the session is a database session), so don't do that.
$session->flush();

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

# Clearing a certain session parameter:
$session->clear(["l_name", "f_name"]);

# Expire '_is_logged_in' flag after 10 idle minutes:
$session->expire('is_logged_in', '+10m')

# Expire the session itself after 1 idle hour:
$session->expire('+1h');

# Delete the session for good:
$session->delete();
$session->flush(); # Recommended practice says use flush() after delete().

DESCRIPTION

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 across HTTP requests. CGI::Session does that and many more.

A Warning about Auto-flushing

As mentioned above in the Synopsis, auto-flushing can be unreliable.

Consequently, you should regard it as mandatory that sessions always need to be explicitly flushed before the program exits.

For instance, in a CGI::Application-based program, sub teardown() would be the appropriate place to do this.

This is all part of what might be called "Object life-cycle 'v' Program life-cycle".

In the simplest case the program has one object of type CGI::Session, and that object is destroyed when the program exits.

If, however, you wish to delete objects explicitly, then each call to delete() should be followed by a call to flush().

Warning: A bug in your logic whereby the DBI handle has gone out out of scope before flush() is called means flush() won't work (when the session is a database session), so don't do that.

For more detail, see the discussion of the delete() method, below.

A Warning about UTF8

Trying to use UTF8 in a program which uses CGI::Session has lead to problems. See RT#21981 and RT#28516.

In the first case the user tried "use encoding 'utf8';" in the program, and in the second case the user tried "$dbh->do(qq|set names 'utf8'|);".

Until this problem is understood and corrected, users are advised to avoid UTF8 in conjunction with CGI::Session.

For details, see: http://rt.cpan.org/Public/Bug/Display.html?id=28516 (and ...id=21981).

TRANSLATIONS

This document is also available in Japanese.

o

Translation based on 4.14: http://digit.que.ne.jp/work/index.cgi?Perldoc/ja

o

Translation based on 3.11, including Cookbook and Tutorial: http://perldoc.jp/docs/modules/CGI-Session-3.11/

TO LEARN MORE

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

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

  • We also provide mailing lists for CGI::Session users. To subscribe to the list or browse the archives visit https://lists.sourceforge.net/lists/listinfo/cgi-session-user

  • RFC 2965 - "HTTP State Management Mechanism" found at ftp://ftp.isi.edu/in-notes/rfc2965.txt

  • CGI - standard CGI library

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

METHODS

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

new()

new( $sid )

new( $query )

new( $dsn, $query||$sid )

new( $dsn, $query||$sid, \%dsn_args )

new( $dsn, $query||$sid, \%dsn_args, \%session_params )

Constructor. Returns new session object, or undef on failure. Error message is accessible through errstr() - class method. If called on an already initialized session will re-initialize the session based on already configured object. This is only useful after a call to load().

Can accept up to three arguments, $dsn - Data Source Name, $query||$sid - query object OR a string representing session id, and finally, \%dsn_args, arguments used by $dsn components.

If called without any arguments, $dsn defaults to driver:file;serializer:default;id:md5, $query||$sid defaults to CGI->new(), and \%dsn_args defaults to undef.

If called with a single argument, it will be treated either as $query object, or $sid, depending on its type. If argument is a string , new() will treat it as session id and will attempt to retrieve the session from data store. If it fails, will create a new session id, which will be accessible through id() method. If argument is an object, cookie() and param() methods will be called on that object to recover a potential $sid and retrieve it from data store. If it fails, new() will create a new session id, which will be accessible through id() method. name() will define the name of the query parameter and/or cookie name to be requested, defaults to CGISESSID.

If called with two arguments first will be treated as $dsn, and second will be treated as $query or $sid or undef, depending on its type. Some examples of this syntax are:

$s = CGI::Session->new("driver:mysql", undef);
$s = CGI::Session->new("driver:sqlite", $sid);
$s = CGI::Session->new("driver:db_file", $query);
$s = CGI::Session->new("serializer:storable;id:incr", $sid);
# etc...

Briefly, new() will return an initialized session object with a valid id, whereas load() may return an empty session object with an undefined id.

Tests are provided (t/new_with_undef.t and t/load_with_undef.t) to clarify the result of calling new() and load() with undef, or with an initialized CGI object with an undefined or fake CGISESSID.

You are strongly advised to run the old-fashioned 'make test TEST_FILES=t/new_with_undef.t TEST_VERBOSE=1' or the new-fangled 'prove -v t/new_with_undef.t', for both new*.t and load*.t, and examine the output.

Following data source components are supported:

  • driver - CGI::Session driver. Available drivers are file, db_file, mysql and sqlite. Third party drivers are welcome. For driver specs consider CGI::Session::Driver

  • serializer - serializer to be used to encode the data structure before saving in the disk. Available serializers are storable, freezethaw and default. Default serializer will use Data::Dumper.

  • id - ID generator to use when new session is to be created. Available ID generator is md5

For example, to get CGI::Session store its data using DB_File and serialize data using FreezeThaw:

$s = new CGI::Session("driver:DB_File;serializer:FreezeThaw", undef);

If called with three arguments, first two will be treated as in the previous example, and third argument will be \%dsn_args, which will be passed to $dsn components (namely, driver, serializer and id generators) for initialization purposes. Since all the $dsn components must initialize to some default value, this third argument should not be required for most drivers to operate properly.

If called with four arguments, the first three match previous examples. The fourth argument must be a hash reference with parameters to be used by the CGI::Session object. (see \%session_params above )

The following is a list of the current keys:

  • name - Name to use for the cookie/query parameter name. This defaults to CGISESSID. This can be altered or accessed by the name accessor.

undef is acceptable as a valid placeholder to any of the above arguments, which will force default behavior.

load()

load( $query||$sid )

load( $dsn, $query||$sid )

load( $dsn, $query, \%dsn_args )

load( $dsn, $query, \%dsn_args, \%session_params )

Accepts the same arguments as new(), and also returns a new session object, or undef on failure. The difference is, new() can create a new session if it detects expired and non-existing sessions, but load() does not.

load() is useful to detect expired or non-existing sessions without forcing the library to create new sessions. So now you can do something like this:

$s = CGI::Session->load() or die CGI::Session->errstr();
if ( $s->is_expired ) {
    print $s->header(),
        $cgi->start_html(),
        $cgi->p("Your session timed out! Refresh the screen to start new session!")
        $cgi->end_html();
    exit(0);
}

if ( $s->is_empty ) {
    $s = $s->new() or die $s->errstr;
}

Notice: All expired sessions are empty, but not all empty sessions are expired!

Briefly, new() will return an initialized session object with a valid id, whereas load() may return an empty session object with an undefined id.

Tests are provided (t/new_with_undef.t and t/load_with_undef.t) to clarify the result of calling new() and load() with undef, or with an initialized CGI object with an undefined or fake CGISESSID.

You are strongly advised to run the old-fashioned 'make test TEST_FILES=t/new_with_undef.t TEST_VERBOSE=1' or the new-fangled 'prove -v t/new_with_undef.t', for both new*.t and load*.t, and examine the output.

id()

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

param($name)

param(-name=>$name)

Used in either of the above syntax returns a session parameter set to $name or undef if it doesn't exist. If it's called on a deleted method param() will issue a warning but return value is not defined.

param($name, $value)

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

Used in either of the above syntax assigns a new value to $name parameter, which can later be retrieved with previously introduced param() syntax. $value may be a scalar, arrayref or hashref.

Attempts to set parameter names that start with _SESSION_ will trigger a warning and undef will be returned.

param_hashref()

Deprecated. Use dataref() instead.

dataref()

Returns reference to session's data table:

$params = $s->dataref();
$sid = $params->{_SESSION_ID};
$name= $params->{name};
# etc...

Useful for having all session data in a hashref, but too risky to update.

save_param()

save_param($query)

save_param($query, \@list)

Saves query parameters to session object. In other words, it's the same as calling param($name, $value) for every single query parameter returned by $query->param(). The first argument, if present, should be either CGI object or any object which can provide param() method. If it's undef, defaults to the return value of query(), which returns CGI->new. If second argument is present and is a reference to an array, only those query parameters found in the array will be stored in the session. undef is a valid placeholder for any argument to force default behavior.

load_param()

load_param($query)

load_param($query, \@list)

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

clear()

clear('field')

clear(\@list)

Clears parameters from the session object.

With no parameters, all fields are cleared. If passed a single parameter or a reference to an array, only the named parameters are cleared.

flush()

Synchronizes data in memory with the copy serialized by the driver. Call flush() if you need to access the session from outside the current session object. You should at least call flush() before your program exits.

As a last resort, CGI::Session will automatically call flush for you just before the program terminates or session object goes out of scope. This automatic behavior was the recommended behavior until the 4.x series. Automatic flushing has since proven to be unreliable, and in some cases is now required in places that worked with 3.x. For further details see:

http://rt.cpan.org/Ticket/Display.html?id=17541
http://rt.cpan.org/Ticket/Display.html?id=17299

Consequently, always explicitly calling flush() on the session before the program exits should be regarded as mandatory until this problem is rectified.

Warning: A bug in your logic whereby the DBI handle has gone out out of scope before flush() is called means flush() won't work (when the session is a database session), so don't do that.

atime()

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

ctime()

Read-only method. Returns the time when the session was first created in seconds from epoch.

expire()

expire($time)

expire($param, $time)

Sets expiration interval relative to atime().

If used with no arguments, returns the expiration interval if it was ever set. If no expiration was ever set, returns undef. For backwards compatibility, a method named etime() does the same thing.

Second form sets an expiration time. This value is checked when previously stored session is asked to be retrieved, and if its expiration interval has passed, it will be expunged from the disk immediately. Passing 0 cancels expiration.

By using the third syntax you can set the expiration interval for a particular session parameter, say ~logged-in. This would cause the library call clear() on the parameter when its time is up. Note it only makes sense to set this value to something earlier than when the whole session expires. Passing 0 cancels expiration.

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

+-----------+---------------+
|   alias   |   meaning     |
+-----------+---------------+
|     s     |   Second      |
|     m     |   Minute      |
|     h     |   Hour        |
|     d     |   Day         |
|     w     |   Week        |
|     M     |   Month       |
|     y     |   Year        |
+-----------+---------------+

Examples:

$session->expire("2h");                # expires in two hours
$session->expire(0);                   # cancel expiration
$session->expire("~logged-in", "10m"); # expires '~logged-in' parameter after 10 idle minutes

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([$name]).

is_new()

Returns true only for a brand new session.

is_expired()

Tests whether session initialized using load() is to be expired. This method works only on sessions initialized with load():

$s = CGI::Session->load() or die CGI::Session->errstr;
if ( $s->is_expired ) {
    die "Your session expired. Please refresh";
}
if ( $s->is_empty ) {
    $s = $s->new() or die $s->errstr;
}

is_empty()

Returns true for sessions that are empty. It's preferred way of testing whether requested session was loaded successfully or not:

$s = CGI::Session->load($sid);
if ( $s->is_empty ) {
    $s = $s->new();
}

Actually, the above code is nothing but waste. The same effect could've been achieved by saying:

$s = CGI::Session->new( $sid );

is_empty() is useful only if you wanted to catch requests for expired sessions, and create new session afterwards. See is_expired() for an example.

delete()

Deletes a session from the data store and empties session data from memory, completely, so subsequent read/write requests on the same object will fail. Technically speaking, though, it will only set the object's status to STATUS_DELETED.

The intention is that in due course (of the program's execution) this will trigger flush(), and flush() will do the actual removal.

However: Auto-flushing can be unreliable, and always explicitly calling flush() on the session after delete() should be regarded as mandatory until this problem is rectified.

Warning: A bug in your logic whereby the DBI handle has gone out out of scope before flush() is called means flush() won't work (when the session is a database session), so don't do that.

find( \&code )

find( $dsn, \&code )

find( $dsn, \&code, \%dsn_args )

Experimental feature. Executes \&code for every session object stored in disk, passing initialized CGI::Session object as the first argument of \&code. Useful for housekeeping purposes, such as for removing expired sessions. Following line, for instance, will remove sessions already expired, but are still in disk:

The following line, for instance, will remove sessions already expired, but which are still on disk:

CGI::Session->find( sub {} );

Notice, above \&code didn't have to do anything, because load(), which is called to initialize sessions inside find(), will automatically remove expired sessions. Following example will remove all the objects that are 10+ days old:

CGI::Session->find( \&purge );
sub purge {
    my ($session) = @_;
    next if $session->is_empty;    # <-- already expired?!
    if ( ($session->ctime + 3600*240) <= time() ) {
        $session->delete() or warn "couldn't remove " . $session->id . ": " . $session->errstr;
    }
}

Note: find will not change the modification or access times on the sessions it returns.

Explanation of the 3 parameters to find():

$dsn

This is the DSN (Data Source Name) used by CGI::Session to control what type of sessions you previously created and what type of sessions you now wish method find() to pass to your callback.

The default value is defined above, in the docs for method new(), and is 'driver:file;serializer:default;id:md5'.

Do not confuse this DSN with the DSN arguments mentioned just below, under \%dsn_args.

\&code

This is the callback provided by you (i.e. the caller of method find()) which is called by CGI::Session once for each session found by method find() which matches the given $dsn.

There is no default value for this coderef.

When your callback is actually called, the only parameter is a session. If you want to call a subroutine you already have with more parameters, you can achieve this by creating an anonymous subroutine that calls your subroutine with the parameters you want. For example:

CGI::Session->find($dsn, sub { my_subroutine( @_, 'param 1', 'param 2' ) } );
CGI::Session->find($dsn, sub { $coderef->( @_, $extra_arg ) } );

Or if you wish, you can define a sub generator as such:

sub coderef_with_args {
    my ( $coderef, @params ) = @_;
    return sub { $coderef->( @_, @params ) };
}

CGI::Session->find($dsn, coderef_with_args( $coderef, 'param 1', 'param 2' ) );
\%dsn_args

If your $dsn uses file-based storage, then this hashref might contain keys such as:

{
    Directory => Value 1,
    NoFlock   => Value 2,
    UMask     => Value 3
}

If your $dsn uses db-based storage, then this hashref contains (up to) 3 keys, and looks like:

{
    DataSource => Value 1,
    User       => Value 2,
    Password   => Value 3
}

These 3 form the DSN, username and password used by DBI to control access to your database server, and hence are only relevant when using db-based sessions.

The default value of this hashref is undef.

Note: find() is meant to be convenient, not necessarily efficient. It's best suited in cron scripts.

MISCELLANEOUS METHODS

remote_addr()

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.

errstr()

Class method. Returns last error message from the library.

dump()

Returns a dump of the session object. Useful for debugging purposes only.

header()

Replacement for CGI.pm'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 = CGI::Cookie->new(-name=>$session->name, -value=>$session->id);
print $cgi->header(-cookie=>$cookie);

You can minimize the above into:

print $session->header();

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

CGI::Session->name("MY_SID");
$session = new CGI::Session(undef, $cgi, \%attrs);

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

query()

Returns query object associated with current session object. Default query object class is CGI.pm.

DEPRECATED METHODS

These methods exist solely for for compatibility with CGI::Session 3.x.

close()

Closes the session. Using flush() is recommended instead, since that's exactly what a call to close() does now.

DISTRIBUTION

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

DRIVERS

Following drivers are included in the standard distribution:

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

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

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

  • sqlite - for storing session data in SQLite. Requires DBI and DBD::SQLite. Full name: CGI::Session::Driver::sqlite

SERIALIZERS

ID GENERATORS

Following ID generators are available:

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

  • incr - generates incremental session ids.

  • static - generates static session ids. CGI::Session::ID::static

CREDITS

CGI::Session evolved to what it is today with the help of following developers. The list doesn't follow any strict order, but somewhat chronological. Specifics can be found in Changes file

Andy Lester
Brian King <mrbbking@mac.com>
Olivier Dragon <dragon@shadnet.shad.ca>
Adam Jacob <adam@sysadminsith.org>
Igor Plisco <igor@plisco.ru>
Mark Stosberg
Matt LeBlanc <mleblanc@cpan.org>
Shawn Sorichetti

COPYRIGHT

Copyright (C) 2001-2005 Sherzod Ruzmetov <sherzodr@cpan.org>. All rights reserved. This library is free software. You can modify and or distribute it under the same terms as Perl itself.

PUBLIC CODE REPOSITORY

You can see what the developers have been up to since the last release by checking out the code repository. You can browse the Subversion repository from here:

http://svn.cromedome.net/repos/CGI-Session

Or check it directly with svn from here:

https://svn.cromedome.net/repos/CGI-Session

SUPPORT

If you need help using CGI::Session consider the mailing list. You can ask the list by sending your questions to cgi-session-user@lists.sourceforge.net .

You can subscribe to the mailing list at https://lists.sourceforge.net/lists/listinfo/cgi-session-user .

Bug reports can be submitted at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Session

AUTHOR

Sherzod Ruzmetov <sherzodr@cpan.org>, http://author.handalak.com/

Mark Stosberg became a co-maintainer during the development of 4.0. markstos@cpan.org. Ron Savage became a co-maintainer during the development of 4.30. rsavage@cpan.org.

SEE ALSO

  • CGI::Session::Tutorial - extended CGI::Session manual

  • RFC 2965 - "HTTP State Management Mechanism" found at ftp://ftp.isi.edu/in-notes/rfc2965.txt

  • CGI - standard CGI library

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