extendsCGI::Session::ErrorHandler
=head1 NAME
CGI::Session - persistent session data in CGI applications
=head1 SYNOPSIS
# Object initialization:
use CGI::Session;
$session = CGI::Session->new();
$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.
$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().
=head1 DESCRIPTION
CGI::Session provides an easy, reliable and modular session management system across HTTP requests.
=head1 METHODS
Following is the overview of all the available methods accessible via CGI::Session object.
=head2 new()
=head2 new( $sid )
=head2 new( $query )
=head2 new( $dsn, $query||$sid )
=head2 new( $dsn, $query||$sid, \%dsn_args )
=head2 new( $dsn, $query||$sid, \%dsn_args, \%session_params )
Constructor. Returns new session object, or undef on failure. Error message is accessible through L<errstr() - class method|CGI::Session::ErrorHandler/"errstr()">. 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 L<load()|/"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 I<driver:file;serializer:default;id:md5>, $query||$sid defaults to C<< CGI->new() >>, and C<\%dsn_args> defaults to I.
If called with a single argument, it will be treated either as C<$query> object, or C<$sid>, depending on its type. If argument is a string , C<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 L<id() method|/"id">. If argument is an object, L<cookie()|CGI/cookie> and L<param()|CGI/param> methods will be called on that object to recover a potential C<$sid> and retrieve it from data store. If it fails, C<new()> will create a new session id, which will be accessible through L<id() method|/"id">. C<name()> will define the name of the query parameter and/or cookie name to be requested, defaults to I.
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, C<new()> will return an initialized session object with a valid id, whereas C<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 C<new()> and C<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:
=over 4
=item *
B - CGI::Session driver. Available drivers are L<file|CGI::Session::Driver::file>, L<db_file|CGI::Session::Driver::db_file>, L<mysql|CGI::Session::Driver::mysql> and L<sqlite|CGI::Session::Driver::sqlite>. Third party drivers are welcome. For driver specs consider L<CGI::Session::Driver|CGI::Session::Driver>
=item *
B - serializer to be used to encode the data structure before saving
in the disk. Available serializers are L<storable|CGI::Session::Serialize::storable>, L<freezethaw|CGI::Session::Serialize::freezethaw> and L<default|CGI::Session::Serialize::default>. Default serializer will use L<Data::Dumper|Data::Dumper>.
=item *
B - ID generator to use when new session is to be created. Available ID generator is L<md5|CGI::Session::ID::md5>
=back
For example, to get CGI::Session store its data using DB_File and serialize data using FreezeThaw:
$s = CGI::Session->new("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 C<\%dsn_args>, which will be passed to C<$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:
=over
=item *
B - Name to use for the cookie/query parameter name. This defaults to CGISESSID. This can be altered or accessed by the C accessor.
=back
undef is acceptable as a valid placeholder to any of the above arguments, which will force default behavior.
=head2 load()
=head2 load( $query||$sid )
=head2 load( $dsn, $query||$sid )
=head2 load( $dsn, $query, \%dsn_args )
=head2 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, L<new()|/"new()"> can create a new session if
it detects expired and non-existing sessions, but C<load()> does not.
C<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 I sessions are empty, but not all I sessions are expired!
Briefly, C<new()> will return an initialized session object with a valid id, whereas C<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 C<new()> and C<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.
=head2 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.
=head2 param($name)
=head2 param(-name=E$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.
=head2 param($name, $value)
=head2 param(-name=E$name, -value=E$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. C<$value>
may be a scalar, arrayref or hashref.
Attempts to set parameter names that start with I<_SESSION_> will trigger
a warning and undef will be returned.
=head2 param_hashref()
B. Use L<dataref()|/"dataref()"> instead.
=head2 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.
=head2 save_param()
=head2 save_param($query)
=head2 save_param($query, \@list)
Saves query parameters to session object. In other words, it's the same as calling L<param($name, $value)|/"param($name)"> for every single query parameter returned by C<< $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 L<query()|/"query()">, which returns C<< 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.
=head2 load_param()
=head2 load_param($query)
=head2 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.
=head2 clear()
=head2 clear('field')
=head2 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.
=head2 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
call flush() sometime 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. Automatic
flushing has proven to be unreliable, and in some cases is now required
in places that worked with CGI::Session 3.x.
Always explicitly calling C<flush()> on the session before the
program exits is recommended. For extra safety, call it immediately after
every important session update.
Also see L
=head2 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.
=head2 ctime()
Read-only method. Returns the time when the session was first created in seconds from epoch.
=head2 expire()
=head2 expire($time)
=head2 expire($param, $time)
Sets expiration interval relative to L<atime()|/"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 C<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 I<~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 I 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:
+-----------+---------------+