# man > CGI::Session::Tutorial

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

## Quick Reference

- `CGI::Session->new()` — Create new session or re-initialize existing one from cookie/query string
- `CGI::Session->load()` — Load existing session only; does not create new session
- `$session->id()` — Return current session ID
- `$session->name()` — Return cookie name (default "CGISESSID")
- `$session->header()` — Return HTTP headers with session cookie
- `$session->param('key', 'value')` — Store data in session
- `$session->param('key')` — Retrieve stored data
- `$session->save_param(['field1', 'field2'])` — Save CGI parameters to session
- `$session->load_param($cgi, ['field'])` — Load session parameters into CGI object
- `$session->clear(['key'])` — Delete specific session parameters (not the session itself)
- `$session->delete()` — Delete session from disk permanently
- `$session->expire('+1h')` — Set session expiration (relative time)
- `$session->expire('param', '5m')` — Set expiration on a specific parameter
- `$session->is_expired()` — Check if session is expired
- `$session->is_empty()` — Check if session object is empty (not loaded)
- `$session->flush()` — Commit session data to store immediately

## Name

**CGI::Session::Tutorial** — Extended CGI::Session manual

## Synopsis

perl
use CGI::Session;

# Create or re-initialize session (defaults: file driver, Data::Dumper serializer)
my $session = CGI::Session->new() or die CGI::Session->errstr;

# Custom driver, serializer, and storage
my $session = CGI::Session->new("driver:mysql;serializer:storable", $sid, {Handle=>$dbh});

# Use a custom CGI object
my $cgi = CGI::Simple->new();
my $session = CGI::Session->new($cgi);

# Load existing session only (no creation)
my $session = CGI::Session->load() or die CGI::Session->errstr;
if ($session->is_expired()) { die "Session expired." }
if ($session->is_empty()) { $session = $session->new(); }

# Send cookie header
print $session->header();
## Methods

### Session Creation and Management

- `CGI::Session->new(undef, undef, {Directory=>'/path'})` — Create session with custom storage directory
- `$session->id()` — Returns the session ID
- `$session->name('newname')` — Get/set cookie name (before new() call to affect new sessions)
- `$session->delete()` — Remove session from disk
- `$session->flush()` — Force write of session data to store
- `$session->expire($time)` — Set session expiration (e.g., `3600`, `'+1h'`, `'+15m'`, `'+1M'`)
- `$session->expire($param, $time)` — Set expiration on a specific parameter
- `$session->is_expired()` — True if session has expired
- `$session->is_empty()` — True if session failed to load (e.g., nonexistent or expired)

### Data Storage and Retrieval

- `$session->param($key)` — Retrieve session parameter
- `$session->param($key, $value)` — Store scalar, arrayref, hashref, or object
- `$session->save_param($cgi, \@list)` — Save CGI parameters into session (omit \@list for all)
- `$session->load_param($cgi, \@list)` — Load session parameters into CGI object
- `$session->clear(\@list)` — Remove specified parameters from session (use with caution: no args clears all)

### Integration

- `$session->header()` — Returns CGI-compatible HTTP header with cookie; arguments forwarded to `CGI::header`
- `HTML::Template->new(associate => $session)` — Bind session to template for `<TMPL_VAR>` access

## Examples

**Create a new session and store user input:**

perl
use CGI::Session;
use CGI;

my $cgi = CGI->new();
my $session = CGI::Session->new($cgi) or die CGI::Session->errstr;
$session->param('username', $cgi->param('username'));
$session->save_param($cgi, ['email', 'lang']);
print $session->header();
**Retrieve and use stored data:**

perl
my $username = $session->param('username');
printf '<input type="text" name="username" value="%s">', $username;
**Expire a specific parameter:**

perl
$session->expire('_profile_access', '1h');
$session->expire('_cc_access', '5m');
**Expire entire session after 30 minutes of inactivity:**

perl
$session->expire('+30m');
**Detect expired session and restart:**

perl
$session = CGI::Session->load() or die CGI::Session->errstr;
if ($session->is_expired()) {
    die "Your session expired. Please refresh your browser.";
}
if ($session->is_empty()) {
    $session = $session->new();  # same driver/serializer config
}
**Enable IP address matching (for environments with static IPs):**

perl
use CGI::Session '-ip_match';
# or
$CGI::Session::IP_MATCH = 1;
## See Also

- [CGI::Session](http://localhost/phpMan.php/perldoc/CGI%3A%3ASession/markdown) — Core module documentation
- [CGI::Session::Driver](http://localhost/phpMan.php/perldoc/CGI%3A%3ASession%3A%3ADriver/markdown) — Driver specification
- [CGI::Session::Driver::file](http://localhost/phpMan.php/perldoc/CGI%3A%3ASession%3A%3ADriver%3A%3Afile/markdown) — Default file driver
- [CGI::Simple](http://localhost/phpMan.php/perldoc/CGI%3A%3ASimple/markdown) — Alternative CGI parser
- [HTML::Template](http://localhost/phpMan.php/perldoc/HTML%3A%3ATemplate/markdown) — Template integration with `associate`
- [RFC 2965](http://www.ietf.org/rfc/rfc2965.txt) — HTTP State Management Mechanism

## Security Notes

- Do not store plaintext passwords in sessions; use one-way hashing if necessary.
- Serializers like `Data::Dumper` produce human-readable output; use `Storable` or `FreezeThaw` for obfuscation.
- Restrict write access to session storage directories.
- Set short expiration times for sensitive applications.
- Session IDs are generated via `Digest::MD5` (32 hex chars) — not easily guessable.
- IP matching (`-ip_match`) can prevent session hijacking but fails with proxies (e.g., AOL).