# man > CGI::Session

---
type: CommandReference
command: CGI::Session
mode: perldoc
section: 3pm
source: perldoc
---

## Quick Reference

- `CGI::Session->new()` — create or retrieve session (defaults: file driver, Data::Dumper serializer, MD5 id)
- `$session->id()` — get the session ID
- `$session->param('key', $value)` — store a value
- `$session->param('key')` — retrieve a value
- `$session->flush()` — synchronize memory to storage (call before exit)
- `$session->delete(); $session->flush()` — remove session from store
- `$session->expire('+1h')` — expire whole session after 1 idle hour
- `$session->expire('is_logged_in', '+10m')` — expire a single parameter after 10 idle minutes

## Name

**CGI::Session** — persistent session data in CGI applications

## Synopsis

perl
use CGI::Session;
$session = CGI::Session->new();
$CGISESSID = $session->id();
print $session->header();

$session->param('f_name', 'Sherzod');
$session->param(-name => 'l_name', -value => 'Ruzmetov');
$session->flush();

my $f_name = $session->param('f_name');
$session->clear(["l_name", "f_name"]);
$session->expire('is_logged_in', '+10m');
$session->expire('+1h');
$session->delete();
$session->flush();
## Methods

### Constructor Methods

- `new($sid | $query | $dsn, ...)` — constructor. Returns a session object (or undef on failure). Creates a new session if none exists or expired. Default DSN: `driver:file;serializer:default;id:md5`. Accepts up to 4 arguments: DSN, query/sid, dsn_args hashref, session_params hashref.
- `load($query | $sid, ...)` — similar to `new()` but does not create a new session if missing or expired. Useful for checking expiration without forcing a new session.
- `$session->id()` — returns the effective session ID (always valid).
- `$session->name($new_name)` — get/set the cookie/query parameter name (default: `CGISESSID`).

### Data Access

- `$session->param($name)` — get a session parameter.
- `$session->param($name, $value)` — set a parameter ($value can be scalar, arrayref, hashref). Names starting with `__SESSION__` are reserved.
- `$session->dataref()` — returns a hashref of all session data (including internal keys like `_SESSION_ID`). Use with caution.
- `$session->save_param($query, \@list)` — save CGI query parameters into the session. If `\@list` provided, only those parameters are saved.
- `$session->load_param($query, \@list)` — load session parameters into a CGI query object.
- `$session->clear('field' | \@list)` — clear specified parameters (or all if no argument).

### Persistence & Lifecycle

- `$session->flush()` — synchronize in-memory data with storage driver. Call explicitly before program exit; auto-flushing is unreliable.
- `$session->delete()` — mark session as deleted. Must call `flush()` to physically remove from store.
- `$session->expire($time)` — set expiration for the whole session (relative to last access time). Pass 0 to cancel.
- `$session->expire($param, $time)` — set expiration for a specific parameter. Time aliases: s, m, h, d, w, M, y.
- `$session->atime()` — read-only: last access time (epoch seconds).
- `$session->ctime()` — read-only: creation time (epoch seconds).
- `$session->is_new()` — true for a brand new session.
- `$session->is_expired()` — true if session loaded via `load()` is expired.
- `$session->is_empty()` — true if session is empty (no data loaded). Not all empty sessions are expired.

### Utility

- `$session->header()` — shortcut for `$cgi->header(-cookie=>$cookie)` using the session cookie.
- `$session->query()` — returns the CGI query object associated with the session.
- `$session->dump()` — returns a dump of the session object (debugging).
- `$session->errstr()` — class method: last error message.
- `$session->ip_match()` — true if `$ENV{REMOTE_ADDR}` matches stored address. Enable with `use CGI::Session '-ip_match'`.
- `$session->find(\&code)` — experimental: iterate over all stored sessions. `$code` receives a session object. Expired sessions are automatically removed.
- `$session->remote_addr()` — returns the remote address recorded at session creation.

### Deprecated Methods

- `close()` — now equivalent to `flush()`.
- `param_hashref()` — use `dataref()` instead.

## Examples

**Create and use a session with custom DSN (MySQL):**

perl
use CGI::Session;
my $session = CGI::Session->new("driver:mysql;serializer:storable;id:md5", $cgi, {
    DataSource => 'dbi:mysql:dbname',
    User       => 'user',
    Password   => 'pass'
});
$session->param('user_id', 42);
$session->flush();
**Check for expired session and force new one:**

perl
my $s = CGI::Session->load() or die CGI::Session->errstr();
if ($s->is_expired) {
    print $s->header(), $cgi->p("Session timed out!");
    exit;
}
if ($s->is_empty) {
    $s = $s->new() or die $s->errstr;
}
**Purge old sessions (cron job):**

perl
CGI::Session->find(sub {
    my ($s) = @_;
    next if $s->is_empty;
    if (($s->ctime + 3600*240) <= time) {
        $s->delete();
        $s->flush();
    }
});
## See Also

- [CGI::Session::Tutorial](http://localhost/phpMan.php/perldoc/CGI%3A%3ASession%3A%3ATutorial/markdown) — extended manual and architecture
- [CGI::Session::Driver](http://localhost/phpMan.php/perldoc/CGI%3A%3ASession%3A%3ADriver/markdown) — driver specification
- [CGI::Cookie](http://localhost/phpMan.php/perldoc/CGI%3A%3ACookie/markdown) — cookie handling
- [Apache::Session](http://localhost/phpMan.php/perldoc/Apache%3A%3ASession/markdown) — alternative session module
- RFC 2109 — [Cookie specification](http://www.ietf.org/rfc/rfc2109.txt)
- RFC 2965 — [Updated cookie spec](http://www.ietf.org/rfc/rfc2965.txt)

## Notes

- **Auto-flushing warning**: Explicit `flush()` is recommended because auto-flushing can fail due to DBI handle going out of scope, circular references, or signal handlers.
- **UTF-8**: Use `use utf8;`, `binmode STDIN/STDOUT ":encoding(utf8)"`, and `$session->header(charset => 'utf-8')` for proper encoding.
- **Session ID**: Always use `$session->id()` to get the valid ID, not a claimed one from the cookie/query.
- **Empty vs. Expired**: All expired sessions are empty, but not all empty sessions are expired.