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           # Warning: A bug in your logic whereby the DBI handle has gone
26           # out of scope before flush() is called means flush() won't work
27           # (when the session is a database session), so don't do that.
28           $session->flush();
29
30           # Retrieving data:
31           my $f_name = $session->param('f_name');
32           # or
33           my $l_name = $session->param(-name=>'l_name');
34
35           # Clearing a certain session parameter:
36           $session->clear(["l_name", "f_name"]);
37
38           # Expire '_is_logged_in' flag after 10 idle minutes:
39           $session->expire('is_logged_in', '+10m')
40
41           # Expire the session itself after 1 idle hour:
42           $session->expire('+1h');
43
44           # Delete the session for good:
45           $session->delete();
46           $session->flush(); # Recommended practice says use flush() after delete().
47

DESCRIPTION

49       CGI-Session is a Perl5 library that provides an easy, reliable and
50       modular session management system across HTTP requests.  Persistency is
51       a key feature for such applications as shopping carts,
52       login/authentication routines, and application that need to carry data
53       across HTTP requests. CGI::Session does that and many more.
54

A Warning about Auto-flushing

56       As mentioned above in the Synopsis, auto-flushing can be unreliable.
57
58       Consequently, you should regard it as mandatory that sessions always
59       need to be explicitly flushed before the program exits.
60
61       For instance, in a "CGI::Application"-based program, "sub teardown()"
62       would be the appropriate place to do this.
63
64       This is all part of what might be called "Object life-cycle 'v' Program
65       life-cycle".
66
67       In the simplest case the program has one object of type CGI::Session,
68       and that object is destroyed when the program exits.
69
70       If, however, you wish to delete objects explicitly, then each call to
71       "delete()" should be followed by a call to "flush()".
72
73       Warning: A bug in your logic whereby the DBI handle has gone out out of
74       scope before flush() is called means flush() won't work (when the
75       session is a database session), so don't do that.
76
77       For more detail, see the discussion of the "delete()" method, below.
78

A Warning about UTF8

80       Trying to use UTF8 in a program which uses CGI::Session has lead to
81       problems. See RT#21981 and RT#28516.
82
83       In the first case the user tried "use encoding 'utf8';" in the program,
84       and in the second case the user tried "$dbh->do(qq|set names
85       'utf8'|);".
86
87       Until this problem is understood and corrected, users are advised to
88       avoid UTF8 in conjunction with CGI::Session.
89
90       For details, see: http://rt.cpan.org/Public/Bug/Display.html?id=28516
91       (and ...id=21981).
92

TRANSLATIONS

94       This document is also available in Japanese.
95
96       o   Translation based on 4.14:
97           http://digit.que.ne.jp/work/index.cgi?Perldoc/ja
98
99       o   Translation based on 3.11, including Cookbook and Tutorial:
100           http://perldoc.jp/docs/modules/CGI-Session-3.11/
101

TO LEARN MORE

103       Current manual is optimized to be used as a quick reference. To learn
104       more both about the philosophy and CGI::Session programming style,
105       consider the following:
106
107       ·   CGI::Session::Tutorial - extended CGI::Session manual. Also
108           includes library architecture and driver specifications.
109
110       ·   We also provide mailing lists for CGI::Session users. To subscribe
111           to the list or browse the archives visit
112           https://lists.sourceforge.net/lists/listinfo/cgi-session-user
113
114       ·   RFC 2965 - "HTTP State Management Mechanism" found at
115           ftp://ftp.isi.edu/in-notes/rfc2965.txt
116
117       ·   CGI - standard CGI library
118
119       ·   Apache::Session - another fine alternative to CGI::Session.
120

METHODS

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

MISCELLANEOUS METHODS

551   remote_addr()
552       Returns the remote address of the user who created the session for the
553       first time. Returns undef if variable REMOTE_ADDR wasn't present in the
554       environment when the session was created.
555
556   errstr()
557       Class method. Returns last error message from the library.
558
559   dump()
560       Returns a dump of the session object. Useful for debugging purposes
561       only.
562
563   header()
564       Replacement for CGI.pm's header() method. Without this method, you
565       usually need to create a CGI::Cookie object and send it as part of the
566       HTTP header:
567
568           $cookie = CGI::Cookie->new(-name=>$session->name, -value=>$session->id);
569           print $cgi->header(-cookie=>$cookie);
570
571       You can minimize the above into:
572
573           print $session->header();
574
575       It will retrieve the name of the session cookie from "$session-"name()>
576       which defaults to $CGI::Session::NAME. If you want to use a different
577       name for your session cookie, do something like following before
578       creating session object:
579
580           CGI::Session->name("MY_SID");
581           $session = new CGI::Session(undef, $cgi, \%attrs);
582
583       Now, $session->header() uses "MY_SID" as a name for the session cookie.
584
585   query()
586       Returns query object associated with current session object. Default
587       query object class is CGI.pm.
588
589   DEPRECATED METHODS
590       These methods exist solely for for compatibility with CGI::Session 3.x.
591
592       close()
593
594       Closes the session. Using flush() is recommended instead, since that's
595       exactly what a call to close() does now.
596

DISTRIBUTION

598       CGI::Session consists of several components such as drivers,
599       serializers and id generators. This section lists what is available.
600
601   DRIVERS
602       Following drivers are included in the standard distribution:
603
604       ·   file - default driver for storing session data in plain files. Full
605           name: CGI::Session::Driver::file
606
607       ·   db_file - for storing session data in BerkelyDB. Requires: DB_File.
608           Full name: CGI::Session::Driver::db_file
609
610       ·   mysql - for storing session data in MySQL tables. Requires DBI and
611           DBD::mysql.  Full name: CGI::Session::Driver::mysql
612
613       ·   sqlite - for storing session data in SQLite. Requires DBI and
614           DBD::SQLite.  Full name: CGI::Session::Driver::sqlite
615
616   SERIALIZERS
617       ·   default - default data serializer. Uses standard Data::Dumper.
618           Full name: CGI::Session::Serialize::default.
619
620       ·   storable - serializes data using Storable. Requires Storable.  Full
621           name: CGI::Session::Serialize::storable.
622
623       ·   freezethaw - serializes data using FreezeThaw. Requires FreezeThaw.
624           Full name: CGI::Session::Serialize::freezethaw
625
626       ·   yaml - serializes data using YAML. Requires YAML or YAML::Syck.
627           Full name: CGI::Session::Serialize::yaml
628
629   ID GENERATORS
630       Following ID generators are available:
631
632       ·   md5 - generates 32 character long hexadecimal string. Requires
633           Digest::MD5.  Full name: CGI::Session::ID::md5.
634
635       ·   incr - generates incremental session ids.
636
637       ·   static - generates static session ids. CGI::Session::ID::static
638

CREDITS

640       CGI::Session evolved to what it is today with the help of following
641       developers. The list doesn't follow any strict order, but somewhat
642       chronological. Specifics can be found in Changes file
643
644       Andy Lester
645       Brian King <mrbbking@mac.com>
646       Olivier Dragon <dragon@shadnet.shad.ca>
647       Adam Jacob <adam@sysadminsith.org>
648       Igor Plisco <igor@plisco.ru>
649       Mark Stosberg
650       Matt LeBlanc <mleblanc@cpan.org>
651       Shawn Sorichetti
652
654       Copyright (C) 2001-2005 Sherzod Ruzmetov <sherzodr@cpan.org>. All
655       rights reserved.  This library is free software. You can modify and or
656       distribute it under the same terms as Perl itself.
657

PUBLIC CODE REPOSITORY

659       You can see what the developers have been up to since the last release
660       by checking out the code repository. You can browse the Subversion
661       repository from here:
662
663        http://svn.cromedome.net/repos/CGI-Session
664
665       Or check it directly with "svn" from here:
666
667        https://svn.cromedome.net/repos/CGI-Session
668

SUPPORT

670       If you need help using CGI::Session consider the mailing list. You can
671       ask the list by sending your questions to
672       cgi-session-user@lists.sourceforge.net .
673
674       You can subscribe to the mailing list at
675       https://lists.sourceforge.net/lists/listinfo/cgi-session-user .
676
677       Bug reports can be submitted at
678       http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Session
679

AUTHOR

681       Sherzod Ruzmetov <sherzodr@cpan.org>, http://author.handalak.com/
682
683       Mark Stosberg became a co-maintainer during the development of 4.0.
684       "markstos@cpan.org".  Ron Savage became a co-maintainer during the
685       development of 4.30. "rsavage@cpan.org".
686

SEE ALSO

688       ·   CGI::Session::Tutorial - extended CGI::Session manual
689
690       ·   RFC 2965 - "HTTP State Management Mechanism" found at
691           ftp://ftp.isi.edu/in-notes/rfc2965.txt
692
693       ·   CGI - standard CGI library
694
695       ·   Apache::Session - another fine alternative to CGI::Session
696
697
698
699perl v5.16.3                      2014-06-10                   CGI::Session(3)
Impressum