1CGI::Session(3)       User Contributed Perl Documentation      CGI::Session(3)
2
3
4

NAME

6       CGI::Session - persistent session data in CGI applications
7

SYNOPSIS

9           # Object initialization:
10           use CGI::Session;
11           $session = new CGI::Session();
12
13           $CGISESSID = $session->id();
14
15           # send proper HTTP header with cookies:
16           print $session->header();
17
18           # storing data in the session
19           $session->param('f_name', 'Sherzod');
20           # or
21           $session->param(-name=>'l_name', -value=>'Ruzmetov');
22
23           # flush the data from memory to the storage driver at least before your
24           # program finishes since auto-flushing can be unreliable
25           $session->flush();
26
27           # retrieving data
28           my $f_name = $session->param('f_name');
29           # or
30           my $l_name = $session->param(-name=>'l_name');
31
32           # clearing a certain session parameter
33           $session->clear(["l_name", "f_name"]);
34
35           # expire '_is_logged_in' flag after 10 idle minutes:
36           $session->expire('is_logged_in', '+10m')
37
38           # expire the session itself after 1 idle hour
39           $session->expire('+1h');
40
41           # delete the session for good
42           $session->delete();
43

DESCRIPTION

45       CGI-Session is a Perl5 library that provides an easy, reliable and mod‐
46       ular session management system across HTTP requests.  Persistency is a
47       key feature for such applications as shopping carts, login/authentica‐
48       tion routines, and application that need to carry data across HTTP
49       requests. CGI::Session does that and many more.
50

TRANSLATIONS

52       This document is also available in Japanese.
53
54       o   Translation based on 4.14:
55           http://digit.que.ne.jp/work/index.cgi?Perldoc/ja
56
57       o   Translation based on 3.11, including Cookbook and Tutorial:
58           http://perldoc.jp/docs/modules/CGI-Session-3.11/
59

TO LEARN MORE

61       Current manual is optimized to be used as a quick reference. To learn
62       more both about the philosophy and CGI::Session programming style, con‐
63       sider the following:
64
65       ·   CGI::Session::Tutorial - extended CGI::Session manual. Also
66           includes library architecture and driver specifications.
67
68       ·   We also provide mailing lists for CGI::Session users. To subscribe
69           to the list or browse the archives visit https://lists.source
70           forge.net/lists/listinfo/cgi-session-user
71
72       ·   RFC 2965 - "HTTP State Management Mechanism" found at
73           ftp://ftp.isi.edu/in-notes/rfc2965.txt
74
75       ·   CGI - standard CGI library
76
77       ·   Apache::Session - another fine alternative to CGI::Session.
78

METHODS

80       Following is the overview of all the available methods accessible via
81       CGI::Session object.
82
83       new()
84
85       new( $sid )
86
87       new( $query )
88
89       new( $dsn, $query⎪⎪$sid )
90
91       new( $dsn, $query⎪⎪$sid, \%dsn_args )
92
93       Constructor. Returns new session object, or undef on failure. Error
94       message is accessible through errstr() - class method. If called on an
95       already initialized session will re-initialize the session based on
96       already configured object. This is only useful after a call to load().
97
98       Can accept up to three arguments, $dsn - Data Source Name, $query⎪⎪$sid
99       - query object OR a string representing session id, and finally,
100       \%dsn_args, arguments used by $dsn components.
101
102       If called without any arguments, $dsn defaults to driver:file;serial‐
103       izer:default;id:md5, $query⎪⎪$sid defaults to "CGI->new()", and
104       "\%dsn_args" defaults to undef.
105
106       If called with a single argument, it will be treated either as $query
107       object, or $sid, depending on its type. If argument is a string ,
108       "new()" will treat it as session id and will attempt to retrieve the
109       session from data store. If it fails, will create a new session id,
110       which will be accessible through id() method. If argument is an object,
111       cookie() and param() methods will be called on that object to recover a
112       potential $sid and retrieve it from data store. If it fails, "new()"
113       will create a new session id, which will be accessible through id()
114       method. "name()" will define the name of the query parameter and/or
115       cookie name to be requested, defaults to CGISESSID.
116
117       If called with two arguments first will be treated as $dsn, and second
118       will be treated as $query or $sid or undef, depending on its type. Some
119       examples of this syntax are:
120
121           $s = CGI::Session->new("driver:mysql", undef);
122           $s = CGI::Session->new("driver:sqlite", $sid);
123           $s = CGI::Session->new("driver:db_file", $query);
124           $s = CGI::Session->new("serializer:storable;id:incr", $sid);
125           # etc...
126
127       Following data source components are supported:
128
129       ·   driver - CGI::Session driver. Available drivers are file, db_file,
130           mysql and sqlite. Third party drivers are welcome. For driver specs
131           consider CGI::Session::Driver
132
133       ·   serializer - serializer to be used to encode the data structure
134           before saving in the disk. Available serializers are storable,
135           freezethaw and default. Default serializer will use Data::Dumper.
136
137       ·   id - ID generator to use when new session is to be created. Avail‐
138           able ID generator is md5
139
140       For example, to get CGI::Session store its data using DB_File and seri‐
141       alize data using FreezeThaw:
142
143           $s = new CGI::Session("driver:DB_File;serializer:FreezeThaw", undef);
144
145       If called with three arguments, first two will be treated as in the
146       previous example, and third argument will be "\%dsn_args", which will
147       be passed to $dsn components (namely, driver, serializer and id genera‐
148       tors) for initialization purposes. Since all the $dsn components must
149       initialize to some default value, this third argument should not be
150       required for most drivers to operate properly.
151
152       undef is acceptable as a valid placeholder to any of the above argu‐
153       ments, which will force default behavior.
154
155       load()
156
157       load($query⎪⎪$sid)
158
159       load($dsn, $query⎪⎪$sid)
160
161       load($dsn, $query, \%dsn_args);
162
163       Accepts the same arguments as new(), and also returns a new session
164       object, or undef on failure.  The difference is, new() can create new
165       session if it detects expired and non-existing sessions, but "load()"
166       does not.
167
168       "load()" is useful to detect expired or non-existing sessions without
169       forcing the library to create new sessions. So now you can do something
170       like this:
171
172           $s = CGI::Session->load() or die CGI::Session->errstr();
173           if ( $s->is_expired ) {
174               print $s->header(),
175                   $cgi->start_html(),
176                   $cgi->p("Your session timed out! Refresh the screen to start new session!")
177                   $cgi->end_html();
178               exit(0);
179           }
180
181           if ( $s->is_empty ) {
182               $s = $s->new() or die $s->errstr;
183           }
184
185       Notice, all expired sessions are empty, but not all empty sessions are
186       expired!
187
188       id()
189
190       Returns effective ID for a session. Since effective ID and claimed ID
191       can differ, valid session id should always be retrieved using this
192       method.
193
194       param($name)
195
196       param(-name=>$name)
197
198       Used in either of the above syntax returns a session parameter set to
199       $name or undef if it doesn't exist. If it's called on a deleted method
200       param() will issue a warning but return value is not defined.
201
202       param($name, $value)
203
204       param(-name=>$name, -value=>$value)
205
206       Used in either of the above syntax assigns a new value to $name parame‐
207       ter, which can later be retrieved with previously introduced param()
208       syntax. $value may be a scalar, arrayref or hashref.
209
210       Attempts to set parameter names that start with _SESSION_ will trigger
211       a warning and undef will be returned.
212
213       param_hashref()
214
215       Deprecated. Use dataref() instead.
216
217       dataref()
218
219       Returns reference to session's data table:
220
221           $params = $s->dataref();
222           $sid = $params->{_SESSION_ID};
223           $name= $params->{name};
224           # etc...
225
226       Useful for having all session data in a hashref, but too risky to
227       update.
228
229       save_param()
230
231       save_param($query)
232
233       save_param($query, \@list)
234
235       Saves query parameters to session object. In other words, it's the same
236       as calling param($name, $value) for every single query parameter
237       returned by "$query->param()". The first argument, if present, should
238       be either CGI object or any object which can provide param() method. If
239       it's undef, defaults to the return value of query(), which returns
240       "CGI->new". If second argument is present and is a reference to an
241       array, only those query parameters found in the array will be stored in
242       the session. undef is a valid placeholder for any argument to force
243       default behavior.
244
245       load_param()
246
247       load_param($query)
248
249       load_param($query, \@list)
250
251       Loads session parameters into a query object. The first argument, if
252       present, should be query object, or any other object which can provide
253       param() method. If second argument is present and is a reference to an
254       array, only parameters found in that array will be loaded to the query
255       object.
256
257       clear()
258
259       clear('field')
260
261       clear(\@list)
262
263       Clears parameters from the session object.
264
265       With no parameters, all fields are cleared. If passed a single parame‐
266       ter or a reference to an array, only the named parameters are cleared.
267
268       flush()
269
270       Synchronizes data in memory  with the copy serialized by the driver.
271       Call flush() if you need to access the session from outside the current
272       session object. You should at least call flush() before your program
273       exits.
274
275       As a last resort, CGI::Session will automatically call flush for you
276       just before the program terminates or session object goes out of scope.
277       This automatic behavior was the recommended behavior until the 4.x
278       series. Automatic flushing has since proven to be unreliable, and in
279       some cases is now required in places that worked with 3.x. For further
280       details see:
281
282        http://rt.cpan.org/Ticket/Display.html?id=17541
283        http://rt.cpan.org/Ticket/Display.html?id=17299
284
285       atime()
286
287       Read-only method. Returns the last access time of the session in sec‐
288       onds from epoch. This time is used internally while auto-expiring ses‐
289       sions and/or session parameters.
290
291       ctime()
292
293       Read-only method. Returns the time when the session was first created
294       in seconds from epoch.
295
296       expire()
297
298       expire($time)
299
300       expire($param, $time)
301
302       Sets expiration interval relative to atime().
303
304       If used with no arguments, returns the expiration interval if it was
305       ever set. If no expiration was ever set, returns undef. For backwards
306       compatibility, a method named "etime()" does the same thing.
307
308       Second form sets an expiration time. This value is checked when previ‐
309       ously stored session is asked to be retrieved, and if its expiration
310       interval has passed, it will be expunged from the disk immediately.
311       Passing 0 cancels expiration.
312
313       By using the third syntax you can set the expiration interval for a
314       particular session parameter, say ~logged-in. This would cause the
315       library call clear() on the parameter when its time is up. Note it only
316       makes sense to set this value to something earlier than when the whole
317       session expires.  Passing 0 cancels expiration.
318
319       All the time values should be given in the form of seconds. Following
320       keywords are also supported for your convenience:
321
322           +-----------+---------------+
323           ⎪   alias   ⎪   meaning     ⎪
324           +-----------+---------------+
325           ⎪     s     ⎪   Second      ⎪
326           ⎪     m     ⎪   Minute      ⎪
327           ⎪     h     ⎪   Hour        ⎪
328           ⎪     d     ⎪   Day         ⎪
329           ⎪     w     ⎪   Week        ⎪
330           ⎪     M     ⎪   Month       ⎪
331           ⎪     y     ⎪   Year        ⎪
332           +-----------+---------------+
333
334       Examples:
335
336           $session->expire("2h");                # expires in two hours
337           $session->expire(0);                   # cancel expiration
338           $session->expire("~logged-in", "10m"); # expires '~logged-in' parameter after 10 idle minutes
339
340       Note: all the expiration times are relative to session's last access
341       time, not to its creation time. To expire a session immediately, call
342       delete(). To expire a specific session parameter immediately, call
343       clear([$name]).
344
345       is_new()
346
347       Returns true only for a brand new session.
348
349       is_expired()
350
351       Tests whether session initialized using load() is to be expired. This
352       method works only on sessions initialized with load():
353
354           $s = CGI::Session->load() or die CGI::Session->errstr;
355           if ( $s->is_expired ) {
356               die "Your session expired. Please refresh";
357           }
358           if ( $s->is_empty ) {
359               $s = $s->new() or die $s->errstr;
360           }
361
362       is_empty()
363
364       Returns true for sessions that are empty. It's preferred way of testing
365       whether requested session was loaded successfully or not:
366
367           $s = CGI::Session->load($sid);
368           if ( $s->is_empty ) {
369               $s = $s->new();
370           }
371
372       Actually, the above code is nothing but waste. The same effect could've
373       been achieved by saying:
374
375           $s = CGI::Session->new( $sid );
376
377       is_empty() is useful only if you wanted to catch requests for expired
378       sessions, and create new session afterwards. See is_expired() for an
379       example.
380
381       delete()
382
383       Deletes a session from the data store and empties session data from
384       memory, completely, so subsequent read/write requests on the same
385       object will fail. Technically speaking, it will only set object's sta‐
386       tus to STATUS_DELETED and will trigger flush(), and flush() will do the
387       actual removal.
388
389       find( \&code )
390
391       find( $dsn, \&code )
392
393       find( $dsn, \&code, \%dsn_args )
394
395       Experimental feature. Executes \&code for every session object stored
396       in disk, passing initialized CGI::Session object as the first argument
397       of \&code. Useful for housekeeping purposes, such as for removing
398       expired sessions. Following line, for instance, will remove sessions
399       already expired, but are still in disk:
400
401       The following line, for instance, will remove sessions already expired,
402       but which are still on disk:
403
404           CGI::Session->find( sub {} );
405
406       Notice, above \&code didn't have to do anything, because load(), which
407       is called to initialize sessions inside find(), will automatically
408       remove expired sessions. Following example will remove all the objects
409       that are 10+ days old:
410
411           CGI::Session->find( \&purge );
412           sub purge {
413               my ($session) = @_;
414               next if $session->is_empty;    # <-- already expired?!
415               if ( ($session->ctime + 3600*240) <= time() ) {
416                   $session->delete() or warn "couldn't remove " . $session->id . ": " . $session->errstr;
417               }
418           }
419
420       Note: find will not change the modification or access times on the ses‐
421       sions it returns.
422
423       Explanation of the 3 parameters to "find()":
424
425       $dsn
426           This is the DSN (Data Source Name) used by CGI::Session to control
427           what type of sessions you previously created and what type of ses‐
428           sions you now wish method "find()" to pass to your callback.
429
430           The default value is defined above, in the docs for method "new()",
431           and is 'driver:file;serializer:default;id:md5'.
432
433           Do not confuse this DSN with the DSN arguments mentioned just
434           below, under \%dsn_args.
435
436       \&code
437           This is the callback provided by you (i.e. the caller of method
438           "find()") which is called by CGI::Session once for each session
439           found by method "find()" which matches the given $dsn.
440
441           There is no default value for this coderef.
442
443           When your callback is actually called, the only parameter is a ses‐
444           sion. If you want to call a subroutine you already have with more
445           parameters, you can achieve this by creating an anonymous subrou‐
446           tine that calls your subroutine with the parameters you want. For
447           example:
448
449               CGI::Session->find($dsn, sub { my_subroutine( @_, 'param 1', 'param 2' ) } );
450               CGI::Session->find($dsn, sub { $coderef->( @_, $extra_arg ) } );
451
452           Or if you wish, you can define a sub generator as such:
453
454               sub coderef_with_args {
455                   my ( $coderef, @params ) = @_;
456                   return sub { $coderef->( @_, @params ) };
457               }
458
459               CGI::Session->find($dsn, coderef_with_args( $coderef, 'param 1', 'param 2' ) );
460
461       \%dsn_args
462           If your $dsn uses file-based storage, then this hashref might con‐
463           tain keys such as:
464
465               {
466                   Directory => Value 1,
467                   NoFlock   => Value 2,
468                   UMask     => Value 3
469               }
470
471           If your $dsn uses db-based storage, then this hashref contains (up
472           to) 3 keys, and looks like:
473
474               {
475                   DataSource => Value 1,
476                   User       => Value 2,
477                   Password   => Value 3
478               }
479
480           These 3 form the DSN, username and password used by DBI to control
481           access to your database server, and hence are only relevant when
482           using db-based sessions.
483
484           The default value of this hashref is undef.
485
486       Note: find() is meant to be convenient, not necessarily efficient. It's
487       best suited in cron scripts.
488

MISCELLANEOUS METHODS

490       remote_addr()
491
492       Returns the remote address of the user who created the session for the
493       first time. Returns undef if variable REMOTE_ADDR wasn't present in the
494       environment when the session was created.
495
496       errstr()
497
498       Class method. Returns last error message from the library.
499
500       dump()
501
502       Returns a dump of the session object. Useful for debugging purposes
503       only.
504
505       header()
506
507       Replacement for CGI.pm's header() method. Without this method, you usu‐
508       ally need to create a CGI::Cookie object and send it as part of the
509       HTTP header:
510
511           $cookie = CGI::Cookie->new(-name=>$session->name, -value=>$session->id);
512           print $cgi->header(-cookie=>$cookie);
513
514       You can minimize the above into:
515
516           print $session->header();
517
518       It will retrieve the name of the session cookie from "$session-"name()>
519       which defaults to $CGI::Session::NAME. If you want to use a different
520       name for your session cookie, do something like following before creat‐
521       ing session object:
522
523           CGI::Session->name("MY_SID");
524           $session = new CGI::Session(undef, $cgi, \%attrs);
525
526       Now, $session->header() uses "MY_SID" as a name for the session cookie.
527
528       query()
529
530       Returns query object associated with current session object. Default
531       query object class is CGI.pm.
532
533       DEPRECATED METHODS
534
535       These methods exist solely for for compatibility with CGI::Session 3.x.
536
537       close()
538
539       Closes the session. Using flush() is recommended instead, since that's
540       exactly what a call to close() does now.
541

DISTRIBUTION

543       CGI::Session consists of several components such as drivers, serializ‐
544       ers and id generators. This section lists what is available.
545
546       DRIVERS
547
548       Following drivers are included in the standard distribution:
549
550       ·   file - default driver for storing session data in plain files. Full
551           name: CGI::Session::Driver::file
552
553       ·   db_file - for storing session data in BerkelyDB. Requires: DB_File.
554           Full name: CGI::Session::Driver::db_file
555
556       ·   mysql - for storing session data in MySQL tables. Requires DBI and
557           DBD::mysql.  Full name: CGI::Session::Driver::mysql
558
559       ·   sqlite - for storing session data in SQLite. Requires DBI and
560           DBD::SQLite.  Full name: CGI::Session::Driver::sqlite
561
562       SERIALIZERS
563
564       ·   default - default data serializer. Uses standard Data::Dumper.
565           Full name: CGI::Session::Serialize::default.
566
567       ·   storable - serializes data using Storable. Requires Storable.  Full
568           name: CGI::Session::Serialize::storable.
569
570       ·   freezethaw - serializes data using FreezeThaw. Requires FreezeThaw.
571           Full name: CGI::Session::Serialize::freezethaw
572
573       ·   yaml - serializes data using YAML. Requires YAML or YAML::Syck.
574           Full name: CGI::Session::Serialize::yaml
575
576       ·   json - serializes data using JSON. Requires JSON::Syck.  Full name:
577           CGI::Session::Serialize::json
578
579       ID GENERATORS
580
581       Following ID generators are available:
582
583       ·   md5 - generates 32 character long hexadecimal string. Requires
584           Digest::MD5.  Full name: CGI::Session::ID::md5.
585
586       ·   incr - generates incremental session ids.
587
588       ·   static - generates static session ids. CGI::Session::ID::static
589

CREDITS

591       CGI::Session evolved to what it is today with the help of following
592       developers. The list doesn't follow any strict order, but somewhat
593       chronological. Specifics can be found in Changes file
594
595       Andy Lester
596       Brian King <mrbbking@mac.com>
597       Olivier Dragon <dragon@shadnet.shad.ca>
598       Adam Jacob <adam@sysadminsith.org>
599       Igor Plisco <igor@plisco.ru>
600       Mark Stosberg
601       Matt LeBlanc <mleblanc@cpan.org>
602       Shawn Sorichetti
603
605       Copyright (C) 2001-2005 Sherzod Ruzmetov <sherzodr@cpan.org>. All
606       rights reserved.  This library is free software. You can modify and or
607       distribute it under the same terms as Perl itself.
608

PUBLIC CODE REPOSITORY

610       You can see what the developers have been up to since the last release
611       by checking out the code repository. You can browse the Subversion
612       repository from here:
613
614        http://svn.cromedome.net/
615
616       Or check it directly with "svn" from here:
617
618        svn://svn.cromedome.net/CGI-Session
619

SUPPORT

621       If you need help using CGI::Session consider the mailing list. You can
622       ask the list by sending your questions to cgi-ses‐
623       sion-user@lists.sourceforge.net .
624
625       You can subscribe to the mailing list at https://lists.source
626       forge.net/lists/listinfo/cgi-session-user .
627
628       Bug reports can be submitted at http://rt.cpan.org/NoAuth/Report
629       Bug.html?Queue=CGI-Session
630

AUTHOR

632       Sherzod Ruzmetov <sherzodr@cpan.org>, http://author.handalak.com/
633
634       Mark Stosberg became a co-maintainer during the development of 4.0.
635       "markstos@cpan.org".
636

SEE ALSO

638       ·   CGI::Session::Tutorial - extended CGI::Session manual
639
640       ·   RFC 2965 - "HTTP State Management Mechanism" found at
641           ftp://ftp.isi.edu/in-notes/rfc2965.txt
642
643       ·   CGI - standard CGI library
644
645       ·   Apache::Session - another fine alternative to CGI::Session
646
647
648
649perl v5.8.8                       2006-11-24                   CGI::Session(3)
Impressum